本文介绍了当没有数据是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行,这是确定的,但医生后抛出一个异常:无效尝试当没有数据是present阅读。
那是不可能的,因为我有在表的用户名= sumant数据。请告诉我是否'如果'语句的正确与否.........
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.
That is not possible as I do have data in table with username=sumant.Please tell me whether the 'if' statement is correct or not.........
和我怎么删除错误??
And how do I remove the error??
推荐答案
您必须调用<$c$c>DataReader.Read$c$c>获取结果:
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返回一个布尔值,表示如果有数据读取更多的块,所以如果你有超过1的结果,你可以这样做:
DataReader.Read returns a boolean 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
}
这篇关于当没有数据是present无效尝试读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!