3

我已成功检查数据库中是否存在值。

这是代码:

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循环。

4

3 回答 3

5

代替

if (!reader.Read())

if (!reader.HasRows)
于 2012-07-12T06:35:08.123 回答
2

我只会有循环,所以你Read一个地方打电话,然后检查count

int count = 0;
while (reader.Read())
{
    ...
}
if (count == 0)
{
    MessageBox.Show(" Can not find user!");
}

我已经删除了这个reader.Close()电话——只要你reader在一个using声明中(它应该是)它就会自动关闭。

于 2012-07-12T07:05:02.013 回答
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;

                    }
                }
于 2012-07-12T06:37:32.680 回答