2016-11-19 92 views

回答

0

这里是我用来从MySQL数据库获取数据的方法。例如: ex)string q =“SELECT ID FROM Users WHERE Username = chris”; string id = dbGetData(q); //用户ID

public static String dbGetData(String q) 
    { 
     openConnection(); //opens connection if closed 
     try 
     { 
      SqlCommand cmd = new SqlCommand(q, connection); 
      return cmd.ExecuteScalar().ToString(); 
     } 
     catch (Exception) 
     { 
     } 
     return null; 
    } 
+0

嗨,克里斯,感谢您的回答。这个SQL语句不是很容易受到SQL注入攻击吗? –

+0

@TiongGor哦,我不确定。如果有人能让我知道这是否属实,那将是一件好事 – chris

0

我不知道这个内置的方法,但是下面的辅助函数将服务宗旨:

private static string GetSqlCommandTextForLogs(SqlCommand cmd) 
{ 
    string text = cmd.CommandText; 
    foreach (SqlParameter parameter in cmd.Parameters) 
    { 
     text = text.Replace("@"+parameter.ParameterName, parameter.Value.ToString()); 
    } 
    return text; 
} 

SelectCommand财产上SqlDataAdapter是类型SqlCommand,并可以传递给这样的帮手,以获得您正在寻找适合日志的文本。

0

你可以用SqlCommandBuilder做到这一点,并取消命令的CommandText。

例子:

using(SqlConnection connection = new SqlConnection("YOUR CONNECTION")) 
    { 
     connection.Open(); 
     SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT ID from SOMETABLE", connection); 

     SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter); 

     Console.WriteLine("SQL SELECT Command is:\n{0}\n", thisAdapter.SelectCommand.CommandText); 

     SqlCommand updateCommand = thisBuilder.GetUpdateCommand(); 
     Console.WriteLine("SQL UPDATE Command is:\n{0}\n", updateCommand.CommandText); 

     SqlCommand insertCommand = thisBuilder.GetInsertCommand(); 
     Console.WriteLine("SQL INSERT Command is:\n{0}\n", insertCommand.CommandText); 

     SqlCommand deleteCommand = thisBuilder.GetDeleteCommand(); 
     Console.WriteLine("SQL DELETE Command is:\n{0}", deleteCommand.CommandText); 
    }