如果在MS Access DB中找不到结果,我如何显示消息框?

时间:2015-05-08 08:11:48

标签: c# ms-access visual-studio-2012

如果在使用C#的MS Access DB中找不到结果,如何显示消息框?

我正在使用此代码进行搜索:

connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "SELECT * FROM Emp WHERE emp_ID LIKE '" + textBox5.Text + "'";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    slip.Text = reader["emp_ID"].ToString(); 
}
connection.Close();                

1 个答案:

答案 0 :(得分:3)

您可以使用HasRows property

  

获取一个值,该值指示OleDbDataReader 是否包含一个   或更多行

if(reader.HasRows)
{

}
else
{
   // Show your message box here
}

此外,您应始终使用parameterized queries。这种字符串连接对SQL Injection攻击开放。

并使用using statement自动处理您的OleDbConnectionOleDbCommandOleDbDataReader,而不是手动调用.Close().Dispose()方法。

using(var connection = new OleDbConnection(conString))
using(var command = connection.CreateCommand())
{
   command.CommandText = "SELECT * FROM Emp WHERE emp_ID LIKE ?";
   command.Parameters.AddWithValue("?", "%" + textBox5.Text + "%");

   using(var reader = command.ExecuteReader())
   {
       if(reader.HasRows)
       {
           while (reader.Read())
           {
                slip.Text = reader["emp_ID"].ToString(); 
           }
       }
       else
       {
            // Show your message box here
       }
   }
}