SqlCommand 参数未正确替换
本文关键字:替换 参数 SqlCommand | 更新日期: 2023-09-27 17:56:34
private SqlCommand createSQLQuery(SqlCommand command)
{
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [skullbase].[dbo].[patients].[name], [skullbase].[dbo].[patients].[dos], [skullbase].[dbo].[patients].[ACC2], [SKULLbase].[dbo].[fullreport].[mrn1], [SKULLbase].[dbo].[fullreport].[ACC], [skullbase].[dbo].[fullreport].[fullreport] FROM [skullbase].[dbo].[fullreport], [skullbase].[dbo].[patients] WHERE ";
int i = 1;
foreach (string word in allTheseWords)
{
command.Parameters.Add("@word" + i.ToString(), SqlDbType.Text).Value = word;
SQLQuery = SQLQuery + " [skullbase].[dbo].[fullreport].[fullreport] LIKE @word" + i.ToString() + " AND ";
i++;
}
SQLQuery = SQLQuery + " skullbase.dbo.patients.ACC2 = skullbase.dbo.fullreport.ACC";
command.CommandText = SQLQuery;
}
MessageBox.Show(command.CommandText.ToString());
return command;
}
以上是我的查询。"字"字不能代替实际值。
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
对于初学者来说,当您在 SQL 命令文本中引用参数引用时(例如 ...[fullreport] = '@word'
...您实际上只是使用文字值'@word'
。 它不会被解释为参数化查询。 为此,您只需使用...[fullreport] = @word
...
其次,我不认为您可以分配多个参数,这些参数名称与在循环中所做的参数名称相同。 添加的每个参数都应具有唯一的名称。
您为每个单词使用相同的参数名称。您应该为每个使用不同的名称。您可以考虑附加索引或其他类似内容,使其成为唯一的参数名称。