我在編程時有點兒不自在,我在想我在這裏做了什麼錯誤 - 有人能幫我嗎?'s'附近的語法不正確。在字符串'''後沒有使用引號'
我正在製作一個控制檯應用程序,它將兩個數據庫同步,但是當我嘗試將數據插入到表中時,它會引發此異常;該代碼是:
public static void AddInterationPath(SqlConnection conDS_ReleaseCri, DataRow dr)
{
SqlCommand insertNewAreaPath = new SqlCommand("INSERT INTO InterationPath (ID,NodePath) VALUES(" + dr[0].ToString() + ",'" + dr[2].ToString() + "')", conDS_ReleaseCriterions);
insertNewAreaPath.ExecuteNonQuery();
}
public static void AddAreaPath(SqlConnection conDS_ReleaseCri, DataRow dr)
{
SqlCommand insertNewAreaPath = new SqlCommand("INSERT INTO AreaPath (ID,NodePath) VALUES(" + dr[0].ToString() + ",'" + dr[2].ToString() + "')", conDS_ReleaseCriterions);
insertNewAreaPath.ExecuteNonQuery();
}
而且我得到以下異常:
不正確的語法近的。「在字符後面沒有顯示的引號 string')'
也許'dr [2]'包含引號?你必須避免引號(在TSQL中簡單地加倍所有單引號) – rabudde
這種代碼很容易被SQL注入。使用[參數化查詢](http://www.dotnetperls.com/sqlparameter)或一個ORM(如LINQ to SQL)來處理轉義參數。 – Adam
更好的解決方案是使用[SQL Transaction](http://www.codeproject.com/Articles/10223/Using-Transactions-in-ADO-NET)和[參數化查詢](http:// www。 dotnetperls.com/sqlparameter)。這將保護您,並允許您一次執行多個查詢,而不會產生巨大的開銷。 – TheGeekZn