我已成功检查数据库中是否有值。
以下是代码:
if (!reader.Read())
{
MessageBox.Show(" Can not find user!");
reader.Close();
}
else
{
int count = 0;
while (reader.Read())
{
string user = (string)reader.GetString(0);
string name = (string)reader.GetString(1);
int roll = (int)reader.GetInt32(2);
string phone = (string)reader.GetString(3);
string address = (string)reader.GetString(4);
string birthofdate = (string)reader.GetString(5);
label1.Text = "" + roll;
label2.Text = name;
label3.Text = birthofdate;
label4.Text = "" + phone;
label5.Text = address;
}
}
但问题是无论如何都会跳过while循环。
答案 0 :(得分:5)
替换
if (!reader.Read())
带
if (!reader.HasRows)
答案 1 :(得分:2)
我会设置循环,以便您在一个位置调用Read
,然后检查count
:
int count = 0;
while (reader.Read())
{
...
}
if (count == 0)
{
MessageBox.Show(" Can not find user!");
}
我已移除reader.Close()
来电 - 只要您的reader
在using
声明中(应该是),它就会自动关闭。
答案 2 :(得分:0)
你不应该使用reader.Read()两次,只使用一次
if (!reader.HasRows)
{
MessageBox.Show(" Can not find user!");
reader.Close();
}
else
{
int count = 0;
while (reader.Read())
{
string user = (string)reader.GetString(0);
string name = (string)reader.GetString(1);
int roll = (int)reader.GetInt32(2);
string phone = (string)reader.GetString(3);
string address = (string)reader.GetString(4);
string birthofdate = (string)reader.GetString(5);
label1.Text = "" + roll;
label2.Text = name;
label3.Text = birthofdate;
label4.Text = "" + phone;
label5.Text = address;
}
}