简体   繁体   English

ListView SELECT查询不返回任何内容

[英]ListView SELECT query not returning anything

I am building a library management software and im trying to search books by name. 我正在构建图书馆管理软件,我正在尝试按名称搜索书籍。 However when I try to use what Ive implemented nothing gets returned. 但是,当我尝试使用已经实现的东西时,什么也不会返回。

This is the code behind used to retrieve data from the db. 这是用于从数据库检索数据的背后代码。

string constr = ConfigurationManager.ConnectionStrings["LibraryContext"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                string bookTitle = Request.QueryString["BookTitle"];
                cmd.Parameters.AddWithValue("@Title", bookTitle); 
                cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE '%@Title%'";
                //cmd.Parameters.AddWithValue("@Title", bookTitle); 
                cmd.Connection = con;

                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    lvCustomers.DataSource = dt;
                    lvCustomers.DataBind();
                }
            }
        }

Thank you for you help 谢谢你的帮助

Do not put quotes around your parameter 不要在参数周围加上引号

cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE %@Title%";

Quotes aroud the parameters tranform everything inside them to a literal string and of course I suppose that you don't have any book whose title is literally "%@Title%" 用引号引起的参数会将它们中的所有内容都转换为文字字符串,当然我想您没有一本书的书名实际上就是“%@ Title%”

also I prefer to use a 我也更喜欢使用

cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE @Title";       
cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = "%" + bookTitle + "%"); 

AddWithValue is a shortcut with numerous drawback that you need to aware of before trying to use it: Can we stop to use AddWithValue already? AddWithValue是一种快捷方式,它有很多缺点,您在使用前需要意识到: 我们可以停止使用AddWithValue吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM