gpt4 book ai didi

c# - 获取查询以使用参数和 "like"

转载 作者:行者123 更新时间:2023-11-30 19:02:21 26 4
gpt4 key购买 nike

我已经看到很多关于在 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();

最佳答案

在上面的代码中,您没有使用 SqlDataAdapter 中的参数,在下面的代码中,您将在命令中使用 SqlDataAdapter。

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

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

**sa.SelectCommand = cmd**

如果您不想使用参数化查询,这将起作用:

 //Declare the connection object
//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 '%" + **txtSearch.Text** + "%')";

//Declare a SQL Adapter
SqlDataAdapter da = new SqlDataAdapter(sql, conn);

关于c# - 获取查询以使用参数和 "like",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13663348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com