【发布时间】:2011-10-27 13:29:18
【问题描述】:
目前我会稍微清理一下我的代码,VS 告诉我,对于 sql 命令,最好使用SqlParameter 而不是复合string。
所以我决定改变我的代码,不幸的是现在我没有得到结果,我不知道为什么。
这是我的一段代码:
...
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetSQLConnectionString());
SqlDataAdapter sqlSelect = new SqlDataAdapter();
try
{
connection.Open();
sqlSelect.SelectCommand = connection.CreateCommand();
sqlSelect.SelectCommand.CommandText = "SELECT id, @FROM AS \"from\", @TO AS \"to\" FROM Dictionary WHERE @FROM LIKE @SEARCHSTRING";
sqlSelect.SelectCommand.Parameters.Add(new SqlParameter("@FROM", this.from));
sqlSelect.SelectCommand.Parameters.Add(new SqlParameter("@TO", this.to));
sqlSelect.SelectCommand.Parameters.Add(new SqlParameter("@SEARCHSTRING", "'%" + this.SearchField.Text + "%'"));
sqlSelect.Fill(dt);
connection.Close();
}
catch(SqlException e)
...
我没有得到任何例外。为什么搜索后dt为空? (使用复合字符串,选择有效。)出了什么问题?
问候
【问题讨论】:
-
添加有效的复合字符串
-
不能将列名作为参数传递
-
SqlParameter方式更干净,我喜欢这样。为什么我的代码不起作用会很有趣。 @Lucas_Santos 我将其更改为列名,但dt仍然为空。问候
标签: c# parameters selectcommand