C# 不存在数据时尝试读取无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1147615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invalid attempt to read when no data is present
提问by knowledgehunter
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.
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.........
当我调试到第 7 行时,没问题,但在那之后 dr 抛出异常:
Invalid attempt to read when no data is present.
这是不可能的,因为我在表中确实有 username=sumant 的数据。请告诉我“如果”语句是否正确.......
And how do I remove the error??
以及如何消除错误?
采纳答案by Julien Poulin
You have to call DataReader.Read
to fetch the result:
您必须调用DataReader.Read
以获取结果:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read())
{
// read data for first record here
}
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:
DataReader.Read()
返回一个bool
指示是否有更多数据块要读取,因此如果您有 1 个以上的结果,您可以执行以下操作:
while (dr.Read())
{
// read data for each record here
}
回答by Colin Mackay
You have to call dr.Read()
before attempting to read any data. That method will return false if there is nothing to read.
您必须dr.Read()
在尝试读取任何数据之前调用。如果没有要读取的内容,该方法将返回 false。
回答by dougczar
I would check to see if the SqlDataReader has rows returned first:
我会检查 SqlDataReader 是否首先返回行:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
...
}
回答by Charlie
I just had this error, I was calling dr.NextResult()
instead of dr.Read()
.
我刚刚遇到了这个错误,我正在调用dr.NextResult()
而不是dr.Read()
.
回答by Aneel Goplani
I used the code below and it worked for me.
我使用了下面的代码,它对我有用。
String email="";
SqlDataReader reader=cmd.ExecuteReader();
if(reader.Read()){
email=reader["Email"].ToString();
}
String To=email;
回答by Dev
I was having 2 values which could contain null values.
我有 2 个可能包含空值的值。
while(dr.Read())
{
Id = dr["Id"] as int? ?? default(int?);
Alt = dr["Alt"].ToString() as string ?? default(string);
Name = dr["Name"].ToString()
}
resolved the issue
解决了问题