2016-11-19 90 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); 
    }