我在识别记录是否有效时遇到错误

时间:2021-12-08 10:34:30

This code is supposed to identify if the record is not existing it will give you the message "Room is invalid!". But when I tried to run the program it would give me the message several times even though the record is already in the database.

此代码用于识别记录是否存在,它将显示消息“房间无效!”。但是当我尝试运行该程序时,即使记录已经在数据库中,它也会多次给我这个消息。

 con.Open();
 cmd = new SqlCommand(@"Select Room_Name From Rooms", con);
 rdr = cmd.ExecuteReader();
 while (rdr.Read())
 {
     roomname = rdr["Room_Name"].ToString();
     if (txtRoom.Text != roomname)
     {
         MessageBox.Show("Room is invalid.");
         txtRoom.Focus();
     }                       
 }
 rdr.Close();
 con.Close();

1 个解决方案

#1


You are reading every record in the database and showing an error on the first invalid match. Filter to your query and use an if instead of a loop

您正在读取数据库中的每条记录,并在第一个无效匹配时显示错误。过滤到您的查询并使用if而不是循环

con.Open();
cmd = new SqlCommand(@"Select Room_Name From Rooms where room_name = @roomName", con);
cmd.Parameters.Add("@roomName", SqlDbType.NVarChar, -1).Value = txtRoom.Text;
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
     roomname = rdr["Room_Name"].ToString();
}
else
{
    MessageBox.Show("Room is invalid.");
    txtRoom.Focus();
}
rdr.Close();
con.Close();

Also, as an aside, wrap the DB stuff in using statements so resources are properly disposed of.

另外,另外,将DB内容包装在using语句中,以便正确处理资源。

#1


You are reading every record in the database and showing an error on the first invalid match. Filter to your query and use an if instead of a loop

您正在读取数据库中的每条记录,并在第一个无效匹配时显示错误。过滤到您的查询并使用if而不是循环

con.Open();
cmd = new SqlCommand(@"Select Room_Name From Rooms where room_name = @roomName", con);
cmd.Parameters.Add("@roomName", SqlDbType.NVarChar, -1).Value = txtRoom.Text;
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
     roomname = rdr["Room_Name"].ToString();
}
else
{
    MessageBox.Show("Room is invalid.");
    txtRoom.Focus();
}
rdr.Close();
con.Close();

Also, as an aside, wrap the DB stuff in using statements so resources are properly disposed of.

另外,另外,将DB内容包装在using语句中,以便正确处理资源。