我在获取以下代码时遇到问题,无法正确添加SqlCommand
参数@vendor
。出于某种原因,传递的查询似乎总是:
select TOP 500 *
from [mike_db].[dbo].[na_pe_sql_import]
where vendname like '%@vendor%';
如果我像这样设置查询,它会起作用,但我知道这是不好的做法:
string strQuery = "select TOP 500 * from [mike_db].[dbo].[na_pe_sql_import] where vendname like '%"+txt_search.Text.ToString()+"%';";
以下是代码:
protected void Search_Click(object sender, EventArgs e)
{
string search = txt_search.Text.ToString();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["mike_db"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
string strQuery = "select TOP 500 * from [mike_db].[dbo].[na_pe_sql_import] where vendname like '%@vendor%';";
cmd = new SqlCommand(strQuery, con);
cmd.Parameters.AddWithValue("vendor", search);
txt_search.Text = string.Empty;
DataSet ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
My_Repeater.DataSource = ds;
My_Repeater.DataBind();
con.Close();
}
答案 0 :(得分:11)
我认为@vendor
在您的查询中被视为文字,而不是参数。
尝试按如下方式定义查询:
string strQuery =
"select TOP 500 * from [mike_db].[dbo].[na_pe_sql_import] where vendname like '%' + @vendor + '%'";
然后添加如下参数:
cmd.Parameters.AddWithValue("@vendor", search);