簡體   English   中英

在數據庫表的所有列和行中搜索文本

[英]Search for text in all columns and rows of a database table

此代碼應在textBox6的所有行和列中查找在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");
   }
}

正如評論中提到的。 您可能想對查詢結果做一些事情,因此您可以使用 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");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM