[英]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.