我正在尝试从我的数据库中检索视频名称,其中视频的主题就像我要搜索的主题一样。
我尝试了 like 查询,但它没有返回值。
能否请您提出建议。
我正在使用 c# 和 sql server。
这是我的代码。
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
string s1 = textBox1.Text;
cmd = new SqlCommand("select Video_Name,subject from Videos where subject like '%"+ s1 +" % ' " ,con);
//cmd = new SqlCommand("select Video_Name from Videos where subject='"+ s1+"' ", con);
SqlDataReader dr = cmd.ExecuteReader();
ArrayList a = new ArrayList();
label2.Visible = true;
label3.Visible = true;
//if (dr.Read())
{
while (dr.Read())
{
a.Add(dr[0].ToString());
}
foreach (string n in a)
{
comboBox1.Items.Add(n);
}
MessageBox.Show("Search succeded");
}
最佳答案
使用参数化查询
string s1 = textBox1.Text;
cmd = new SqlCommand("select Video_Name,subject from Videos where subject like @video",con);
cmd.Parameters.AddWithValue("@video", "%" + s1 + "%");
这样你就避免了 Sql Injection问题,您的命令文本更具可读性。
这也有助于格式化您的命令文本,而不会出现细微的键入错误,也无需在字符串周围添加引号。使用参数,正确引用参数值的负担将传递给更了解如何正确执行的框架代码。
顺便说一句,您可以避免将 combobox.Datasource 属性设置为 ArrayList 变量 a
的第二个循环
comboBox1.Datasource = a;
关于c# - 类似sql的查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20798202/