Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用SQL Server在ASP.NET中获取like运算符时出错_C#_Sql_Asp.net - Fatal编程技术网

C# 使用SQL Server在ASP.NET中获取like运算符时出错

C# 使用SQL Server在ASP.NET中获取like运算符时出错,c#,sql,asp.net,C#,Sql,Asp.net,我正在使用一个代码,以获得城市名称与喜欢的关键字,但没有显示任何结果 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);

我正在使用一个代码,以获得城市名称与喜欢的关键字,但没有显示任何结果

 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);

有人能给出这个问题的解决方案吗?

在参数化查询中,像一样添加的正确方法是第一次更改:

SqlCommand cmd = new SqlCommand("select top 10 City from tbl_City where City like @Name+'%'", con);
致:

然后改变这个:

cmd.Parameters.AddWithValue("@Name", prefixText);
致:


哪个错误?顺便说一句,您是否将%添加到C#中的prefixText而不是SQL代码中?请记住,直接在查询中添加参数是一种不好的做法,会使代码容易受到攻击(例如SQL注入)
cmd.Parameters.AddWithValue("@Name", prefixText);
cmd.Parameters.AddWithValue("@Name", prefixText + "%");
    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);