我正在尝试从我的数据库中检索视频名称,其中视频的主题就像我要搜索的主题.
我尝试类似的查询,但它不是返回值.
能否提出建议?
我正在使用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");
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*eve 10
使用参数化查询
string s1 = textBox1.Text;
cmd = new SqlCommand("select Video_Name,subject from Videos where subject like @video",con);
cmd.Parameters.AddWithValue("@video", "%" + s1 + "%");
Run Code Online (Sandbox Code Playgroud)
这样可以避免Sql Injection问题,并且命令文本更具可读性.
这也有助于格式化命令文本而不会出现细微的输入错误,也无需在字符串周围添加引号.使用参数,正确引用参数值的负担将传递给更好地了解如何正确执行的框架代码.
顺便说一下,你可以避免第二个循环将combobox.Datasource属性设置为ArrayList变量 a
comboBox1.Datasource = a;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |