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
}
这篇关于不存在数据时尝试读取无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不存在数据时尝试读取无效


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01