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

Invalid attempt to read when no data is present(不存在数据时尝试读取无效)
本文介绍了不存在数据时尝试读取无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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
}

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)