[英]Is it possible to parameterize table and column names in SQLite queries?
我試圖從C#在SQLite中執行參數化查詢,並且im使用的方法是使用以下方法創建靜態命令:
SQLiteCommand cmd = new SQLiteCommand(
"SELECT [ID]" +
",[email]" +
",[serializedata]" +
",[restrictions]" +
" FROM " + UserTable +
" WHERE @search = @searchparam", SQLConnection);
cmd.Parameters.Add(new SQLiteParameter("@searchparam"));
cmd.Parameters.Add(new SQLiteParameter("@search"));
並這樣稱呼它:
Command.Parameters["@searchparam"].Value = searchdata;
Command.Parameters["@search"].Value = search;
SQLiteDataAdapter slda = new SQLiteDataAdapter(UserSelectUsernameCommand);
DataSet ds = new DataSet();
slda.Fill(ds);
User[] array = new User[ds.Tables[0].Rows.Count];
int index = 0;
foreach (DataRow row in ds.Tables[0].Rows)
{
array[index] = new User(this, row);
index++;
}
return array;
但是我在“'@search'不是正確的列名”之類的地方出現錯誤或類似的東西。 如果我使用恆定的列名,並且僅使用數據作為參數,那么它可以工作,但是當我需要按不同的列名進行搜索時,我不想創建10個不同的命令。
這是什么問題?
通常, 無法對諸如列名(或表名)之類的參數進行參數化-並且存在不同的索引這一事實意味着該索引必須在內部采用不同的計划。 因此,您將必須使用串聯- 但要小心地將已知的列名列入白名單以防止sql注入:
SQLiteCommand cmd = new SQLiteCommand(@"
SELECT [ID],[email],[serializedata],[restrictions]
FROM " + whiteListedUserTable + @"
WHERE [" + whiteListedColumnName + @"] = @searchparam", SQLConnection);
cmd.Parameters.Add(new SQLiteParameter("@searchparam"));
...
Command.Parameters["@searchparam"].Value = searchdata;
您不能以這種方式使用查詢參數-表示列名。 您只能使用它來提供值。
考慮這樣的事情:
SQLiteCommand cmd = new SQLiteCommand(
"SELECT [ID]" +
",[email]" +
",[serializedata]" +
",[restrictions]" +
" FROM " + UserTable +
" WHERE [" + search + "] = @searchparam", SQLConnection);
cmd.Parameters.Add(new SQLiteParameter("@searchparam"));
如果您控制此功能的所有輸入,並且如果您以外的其他人不能提供該輸入,那應該是安全的。 但是,如果search
來自不受信任的第三方,請確保對值進行適當的安全檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.