当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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%"

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?

分享给朋友:
您可能感兴趣的文章:
随机阅读: