【问题标题】:Search for text in all columns and rows of a database table在数据库表的所有列和行中搜索文本
【发布时间】:2020-10-09 12:28:48
【问题描述】:

此代码应在表格的所有行和列中找到在textBox6 中输入的单词。编译器不会发出错误,但代码本身不会搜索。很可能是错误的语法或错误的 sql 查询。

private void button5_Click(object sender, EventArgs e)
{
   if (textBox6.Text != "")
   {
       sqlcon.Open();
       SqlCommand query = new SqlCommand("SELECT * FROM  Info WHERE (SurName LIKE '%" + textBox6.Text + "%' OR Name LIKE '%" + textBox6.Text + "%' OR MiddleName LIKE '%" + textBox6.Text + "%' OR OfficePhone  LIKE '%" + textBox6.Text + "%' OR MobilePhone LIKE '%" + textBox6.Text + "%' OR IDDolj LIKE '%" + textBox6.Text + "%')", sqlcon);
       query.ExecuteNonQuery();
       sqlcon.Close();
   }
   else
   {
       MessageBox.Show("Error");
   }
}

【问题讨论】:

  • 使用参数!
  • 您执行查询但不检查它的结果。

标签: c# sql database


【解决方案1】:

如 cmets 中所述。您可能想对查询结果做一些事情,因此您可以使用 ExecuteReader() 来代替使用 ExecuteNonQuery()。

我也肯定会使用 SqlParameters 来防止 SQLInjection。

private void button5_Click(object sender, EventArgs e)
{
    if (!String.IsNullOrEmpty(textBox6.Text))
    {
        sqlcon.Open();
        SqlCommand query = new SqlCommand("SELECT * FROM Info WHERE (SurName LIKE @searchText OR Name LIKE @searchText OR MiddleName LIKE @searchText OR OfficePhone  LIKE @searchText OR MobilePhone LIKE @searchText OR IDDolj LIKE @searchText)", sqlcon);
        SqlParameter searchTextParam = new SqlParameter("searchText", "%" + textBox6.Text + "%");
        query.Parameters.Add(searchTextParam);
        DataReader results = query.ExecuteReader();
        // Do something with the results here.
        sqlcon.Close();
    }
    else
    {
        MessageBox.Show("Error");
    }
}

【讨论】:

    猜你喜欢
    • 2012-11-10
    • 1970-01-01
    • 2012-08-16
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多