的SqlCommand参数不能正常工作 [英] SqlCommand parameters aren't working properly
问题描述
考虑以下code:
SqlConnection conn = new SqlConnection(@"connection string");
SqlCommand ourCommand = new SqlCommand(String.Format(
@"SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE '@FL1'"), conn);
ourCommand.CommandTimeout = 6000;
ourCommand.Parameters.AddWithValue("@FL1", TextBox1.Text);
SqlDataAdapter adapter = new SqlDataAdapter(ourCommand);
DataTable dt = new DataTable();
conn.Open();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
问题是,数据表
是空的 - 这意味着该命令要么没有执行或生成不正确的查询。我在想什么?连接和查询是有效的。不带参数的命令也适用。数据库引擎是SQL Server 2008 R2的
The problem is that datatable
is empty - which means the command either was not executed or incorrect query was generated. What am I missing? Connection and query are valid. The command without parameter also works. Database engine is SQL Server 2008 R2
推荐答案
您已经把参数名在引号,因此它被视为一个的值的,而不是作为一个参数。试试这个:
You've put the parameter name in quotes, so it's being treated as a value, not as a parameter. Try this instead:
"SELECT Field1,Field2,Field3 FROM Tbl WHERE Field1 LIKE @FL1"
(其实我想到您现有的code抛出异常既然你提供更多的参数比都在SQL ......)
(I'd actually expect your existing code to throw an exception given that you're supplying more parameters than are in the SQL...)
正如评论指出的那样,你不需要的String.Format
或者
As noted in comments, you don't need the string.Format
either.
这篇关于的SqlCommand参数不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!