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
}
这篇关于不存在数据时尝试读取无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不存在数据时尝试读取无效
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
