2017-05-08 55 views
0
string sql = "Insert Into mytable" + $" (Id, Name, otherName) Values" + 
      $" ('{id}','{name}','{otherName}')"; 
using (SqlCommand cmd = new SqlCommand(sql, sqlConnection)) 
     { 
      cmd.ExecuteNonQuery(); 
     } 

而且我的問題是:我的一些數據有東西,如:在‘中文別名’列,其中會有一些類似‘邁克的車’。 SQL服務器會將錯誤放在「's」上,我不知道如何解決我的代碼。的Microsoft SQL Server:INSERT到表的

謝謝您的閱讀。併爲我的英語不好而感到抱歉。

+0

取代'邁克的car'嘗試'邁克'的car'兩個單引號。而您必須改用參數化查詢。 –

+2

[在C#中使用SqlCommand準備的優缺點]可能的副本(http://stackoverflow.com/questions/2449827/pros-and-cons-of-using-sqlcommand-prepare-in-c) –

+0

感謝回覆,但我正在做的是解析數據來源,我沒有任何控制它。所以,我需要弄清楚如何用代碼解決這個問題。順便說一下,如何以這種方式進行參數化? – maxrena

回答

2

您需要使用的參數,你離開自己開放到SQL注入攻擊:

// These come from whatever your source which you have no control over. 
int id = 12345; 
string name = "Andrew"; 
string otherName = "Fred"; 

var sql = "Insert Into mytable (Id, Name, otherName) Values (@id, @name, @otherName) 
using (var sqlQuery = new SqlCommand(sql, sqlConnection)) 
{ 

    sqlQuery.Parameters.AddWithValue("@id", id); 
    sqlQuery.Parameters.AddWithValue("@name", name); 
    sqlQuery.Parameters.AddWithValue("@otherName", otherName); 

    sqlQuery.ExecuteNonQuery(); 
} 
+1

只是想補充一下這是正確答案的原因:參數知道如何正確處理(轉義)值,使得沒有值可以破壞您的SQL命令。 –

+0

非常感謝你,我感謝你的幫助。 – maxrena