不存在数据时尝试读取无效 [英] Invalid attempt to read when no data is present

查看:24
本文介绍了不存在数据时尝试读取无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    private void button1_Click(object sender, EventArgs e)
    {
        string name;
        name = textBox5.Text;
        SqlConnection con10 = new SqlConnection("con strn");
        SqlCommand cmd10 = new SqlCommand("select * from sumant where username=@name");
        cmd10.Parameters.AddWithValue("@name",name);
        cmd10.Connection = con10;
        cmd10.Connection.Open();//line 7
        SqlDataReader dr = cmd10.ExecuteReader();
    }

    if ( textBox2.Text == dr[2].ToString())
    {
        //do something;
    }

当我调试到第 7 行时,一切正常,但之后 dr 抛出异常:

When I debug until line 7, it is OK, but after that dr throws an exception:

不存在数据时尝试读取无效.

Invalid attempt to read when no data is present.

我不明白为什么会出现该异常,因为我的表中有用户名=sumant 的数据.

I don't understand why I'm getting that exception, since I do have data in the table with username=sumant.

请告诉我if"语句是否正确.以及如何修复错误?

Please tell me whether the 'if' statement is correct or not. And how do I fix the error?

推荐答案

你必须调用 DataReader.Read 获取结果:

You have to call DataReader.Read to fetch the result:

SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read()) 
{
    // read data for first record here
}

DataReader.Read() 返回一个 bool 指示是否有更多的数据块要读取,所以如果你有超过 1 个结果,你可以这样做:

DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:

while (dr.Read()) 
{
    // read data for each record here
}

这篇关于不存在数据时尝试读取无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆