我有一個具有不同 id 的專案串列,它們代表 SQL 表的 PK 值。有什么方法可以建立一個有效和安全的陳述句?
從現在開始,我總是準備一個代表陳述句的字串,并在我通過 foreach 回圈遍歷串列時構建它。
這是我正在做的一個例子:
string update = "UPDATE table SET column = 0 WHERE";
foreach (Line l in list)
{
update = " id = " l.Id " OR";
}
// To remove last OR
update.Remove(update.Length - 3);
MySqlHelper.ExecuteNonQuery("myConnectionString", update);
這感覺很不安全,看起來很丑陋。
有沒有更好的方法呢?
uj5u.com熱心網友回復:
所以,是的,在 SQL 中你有'IN'關鍵字,它允許你指定一組值。
這應該可以完成您想要的(語法可能有問題,但想法就在那里)
var ids = string.Join(',', list.Select(x => x.Id))
string update = $"UPDATE table SET column = 0 WHERE id IN ({ids})";
MySqlHelper.ExecuteNonQuery("myConnectionString", update);
但是,您執行 SQL 的方式可能被認為是危險的(您應該沒問題,因為這看起來就像來自資料庫的 id,誰知道呢,安全總比抱歉好)。在這里,您將引數直接傳遞到查詢字串中,這對 SQL 注入是非常危險的潛在風險。有一些方法可以解決這個問題,并使用內置的 .NET 'SqlCommand' 物件
https://www.w3schools.com/sql/sql_injection.asp
https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand?view=dotnet-plat-ext-6.0
uj5u.com熱心網友回復:
使用IN運算子會更有效:
string update = "UPDATE table SET column = 0 WHERE id IN (";
foreach (Line l in list)
{
update = l.Id ",";
}
// To remove last comma
update.Remove(update.Length - 1);
// To insert closing bracket
update = ")";
uj5u.com熱心網友回復:
如果使用 .NET Core Framework,請參閱以下為 WHERE IN 創建引數的庫。該庫是我 4.7 年前在 Framework 中撰寫的 VB.NET 的一個埠。克隆存盤庫,獲取SqlCoreUtilityLibrary用于創建陳述句的專案。
設定。
public void UpdateExample()
{
var identifiers = new List<int>() { 1, 3,20, 2, 45 };
var (actual, exposed) = DataOperations.UpdateExample(
"UPDATE table SET column = 0 WHERE id IN", identifiers);
Console.WriteLine(actual);
Console.WriteLine(exposed);
}
足夠的代碼來創建引數化 SQL 陳述句。注意ActualCommandText 方法包含用于開發,而不是用于生產,因為它顯示引數的實際值。
public static (string actual, string exposed) UpdateExample(string commandText, List<int> identifiers)
{
using var cn = new SqlConnection() { ConnectionString = GetSqlConnection() };
using var cmd = new SqlCommand() { Connection = cn };
cmd.CommandText = SqlWhereInParamBuilder.BuildInClause(commandText " ({0})", "p", identifiers);
cmd.AddParamsToCommand("p", identifiers);
return (cmd.CommandText, cmd.ActualCommandText());
}
對于一個真正的應用程式,所有代碼都將在上面的方法中完成,而不是回傳兩個字串。
結果
UPDATE table SET column = 0 WHERE id IN (@p0,@p1,@p2,@p3,@p4)
UPDATE table SET column = 0 WHERE id IN (1,3,20,2,45)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454339.html
