InvalidOperationException:不存在数据时尝试读取无效。 (SQL)
SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString);
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.Parameters.Add("@ThreadsID", SqlDbType.Int).Value = commentIDe;
cmd.Parameters.Add("@CommentsID", SqlDbType.Int).Value = commentIDe;
try
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr != null && dr["Comments"] != null && dr["Name"] != null && dr["Date"] != null && dr["UserID"]!=null)//> Invalid attempt to read when no data is present.
{
Comment = dr["Comments"].ToString();
UserName = dr["Name"].ToString();
Reputation=Int32.Parse(dr["Reputation"].ToString());
Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
UserID = (Guid)dr["UserID"];
}
dr.Close();
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
注意:我确实使用 while(dr.Read){} 迭代了那段代码...此处未显示。
为什么我会收到该异常以及如何摆脱它
更新:
while (reader.Read())//Command runs through all the ThreadIDs that i have!
{
Comments allQ = new Comments((int)reader["CommentsID"]);
allComments.Add(allQ);
}
注释是代码所在的类,并且它在构造函数内有一个方法来运行我提供的代码。
可能是如果循环运行太多次..那么就会抛出异常,对吗?
SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString);
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.Parameters.Add("@ThreadsID", SqlDbType.Int).Value = commentIDe;
cmd.Parameters.Add("@CommentsID", SqlDbType.Int).Value = commentIDe;
try
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr != null && dr["Comments"] != null && dr["Name"] != null && dr["Date"] != null && dr["UserID"]!=null)//> Invalid attempt to read when no data is present.
{
Comment = dr["Comments"].ToString();
UserName = dr["Name"].ToString();
Reputation=Int32.Parse(dr["Reputation"].ToString());
Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
UserID = (Guid)dr["UserID"];
}
dr.Close();
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
Note: I do iterate over that piece of code with while(dr.Read){}... it isnt shown here.
Why do i get that exception and how do i get rid of it
UPDATE:
while (reader.Read())//Command runs through all the ThreadIDs that i have!
{
Comments allQ = new Comments((int)reader["CommentsID"]);
allComments.Add(allQ);
}
Comments is the class that the code is in, and it has a method inside the constructor that runs the code that i presented.
It could be that if the loop runs too many times.. Then the exception is being thrown am i right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码的以下部分是非法的
您必须在访问 SqlDataReader 的索引器之前调用一次 Read 方法(并验证它是否返回 true),如文档所述:
The following part of your code is illegal
You have to call the Read method once (and verify that it returns true) before accessing the indexer of the SqlDataReader, as the documentation states: