不存在数据时尝试读取无效
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
抛出异常:
当不存在数据时,读取尝试无效。
我不明白为什么我会得到这个异常,因为我的表中确实有用户名 = sumant 的数据。
请告诉我“if”语句是否正确。 我该如何修复该错误?
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;
}
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.
I don't understand why I'm getting that exception, since I do have data in the table with username=sumant.
Please tell me whether the 'if' statement is correct or not. And how do I fix the error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在尝试读取任何数据之前,您必须调用
dr.Read()
。 如果没有任何内容可读取,该方法将返回 false。You have to call
dr.Read()
before attempting to read any data. That method will return false if there is nothing to read.我刚刚遇到此错误,我调用的是
dr.NextResult()
而不是dr.Read()
。I just had this error, I was calling
dr.NextResult()
instead ofdr.Read()
.我会检查 SqlDataReader 是否首先返回行:
I would check to see if the SqlDataReader has rows returned first:
我使用了下面的代码,它对我有用。
I used the code below and it worked for me.
我有 2 个可能包含空值的值。
解决了问题
I was having 2 values which could contain null values.
resolved the issue
您必须致电
DataReader.Read()
获取结果:DataReader.Read()
返回一个bool
指示是否还有更多数据块要读取,因此如果您有超过 1 个结果,您可以执行以下操作:You have to call
DataReader.Read()
to fetch the result:DataReader.Read()
returns abool
indicating if there are more blocks of data to read, so if you have more than 1 result, you can do: