我正在使用代码来获取具有相似关键字但未显示任何结果的城市名称
SqlConnection con = new SqlConnection(tempPath);
con.Open();
SqlCommand cmd = new SqlCommand("select top 10 City from tbl_City where City like @Name+'%'", con);
cmd.Parameters.AddWithValue("@Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
任何人都可以解决这个问题吗?
答案 0 :(得分:4)
在参数化查询中添加LIKE
的正确方法是首先更改:
SqlCommand cmd = new SqlCommand("select top 10 City from tbl_City where City like @Name+'%'", con);
致:
SqlCommand cmd = new SqlCommand("select top 10 City from tbl_City where City like @Name", con);
然后改变这个:
cmd.Parameters.AddWithValue("@Name", prefixText);
到:
cmd.Parameters.AddWithValue("@Name", prefixText + "%");
答案 1 :(得分:0)
SqlConnection con = new SqlConnection(tempPath);
con.Open();
SqlCommand cmd = new SqlCommand("select top 10 City from tbl_City where City like '"+ prefix+"%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);