我已经看到了很多关于在 Sql 查询和“like”中使用参数的问题,但我已经尝试了所有我见过的编码方式,但仍然无法让我的查询给出结果。如果我在查询本身中输入一个值,它运行良好。当我运行列出的第一个查询时,我收到错误“必须声明标量变量“@Search”,但我认为我是使用 cmd.Parameters.AddWithValue 语句做到的。谁能看到我可能做错了什么?感谢任何帮助.
//Declare the connection object
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
//Connect to the db
Conn.Open();
//Define query
//This query doesn't work
string sql = "SELECT CustomerID, LastName, FirstName, Email, Password, Address1, Address2, City, State, Zip, Phone, Fax FROM Customer WHERE (State LIKE '%' + @Search + '%')";
//This query doesn't work either
string sql = "SELECT CustomerID, LastName, FirstName, Email, Password, Address1, Address2, City, State, Zip, Phone, Fax FROM Customer WHERE State LIKE @Search";
//This query works
string sql = "SELECT CustomerID, LastName, FirstName, Email, Password, Address1, Address2, City, State, Zip, Phone, Fax FROM Customer WHERE State LIKE 'MI'";
//Declare the Command
SqlCommand cmd = new SqlCommand(sql, Conn);
//Add the parameters needed for the SQL query
cmd.Parameters.AddWithValue("@Search", "%" + txtSearch.Text + "%");
//Declare a SQL Adapter
SqlDataAdapter da = new SqlDataAdapter(sql, Conn);
//Declare a DataTable
DataTable dt = new DataTable();
//Populate the DataTable
da.Fill(dt);
//Bind the Listview
lv.DataSource = dt;
lv.DataBind();
dt.Dispose();
da.Dispose();
Conn.Close();