InvalidOperationException:不存在数据时尝试读取无效。 (SQL)
void ExecuteContent()
{
StringBuilder sb = new StringBuilder();
sb.Append("SELECT TOP 1 @UsersID,u.Avatar,t.Date, u.Name, t.ThreadTitle, t.ThreadParagraph");
sb.Append(" FROM Users as u");
sb.Append(" INNER JOIN Threads as t ON u.UsersID = t.UsersID");
sb.Append(" Where @UsersID=t.UsersID");
sb.Append(" ORDER BY t.Date DESC");
using (SqlConnection conn = new SqlConnection(AnswerQuestion.connectionString))
{
conn.Open();
SqlCommand sqlComm = new SqlCommand(sb.ToString(), conn);
MembershipUser CurrentUser = Membership.GetUser();
Guid i = (Guid)CurrentUser.ProviderUserKey;
sqlComm.Parameters.Add("@UsersID", SqlDbType.UniqueIdentifier).Value = i;
SqlDataReader dr = sqlComm.ExecuteReader();
UserName = dr["Name"].ToString();//The exception is thrown here
Image = (Image) dr["Avatar"];
ThreadTitle = dr["ThreadTitle"].ToString();
ThreadParagraph = dr["ThreadParagraph"].ToString();
Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
}
}
我不明白为什么我得到它。我想做的就是找到最后一个发布该线程的人..我查看了调试,一切似乎都很好。我还查看了 Visual Studio 2010 中的 sql server.. 有数据,但不知何故它没有被读取并且抛出异常...:(
void ExecuteContent()
{
StringBuilder sb = new StringBuilder();
sb.Append("SELECT TOP 1 @UsersID,u.Avatar,t.Date, u.Name, t.ThreadTitle, t.ThreadParagraph");
sb.Append(" FROM Users as u");
sb.Append(" INNER JOIN Threads as t ON u.UsersID = t.UsersID");
sb.Append(" Where @UsersID=t.UsersID");
sb.Append(" ORDER BY t.Date DESC");
using (SqlConnection conn = new SqlConnection(AnswerQuestion.connectionString))
{
conn.Open();
SqlCommand sqlComm = new SqlCommand(sb.ToString(), conn);
MembershipUser CurrentUser = Membership.GetUser();
Guid i = (Guid)CurrentUser.ProviderUserKey;
sqlComm.Parameters.Add("@UsersID", SqlDbType.UniqueIdentifier).Value = i;
SqlDataReader dr = sqlComm.ExecuteReader();
UserName = dr["Name"].ToString();//The exception is thrown here
Image = (Image) dr["Avatar"];
ThreadTitle = dr["ThreadTitle"].ToString();
ThreadParagraph = dr["ThreadParagraph"].ToString();
Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
}
}
I dont understand why I get it. All i am trying to do is to get the last person who posted the thread.. I looked at debugging, and things seem fine. I also looked at the sql server in visual studio 2010.. there is data,,but somehow it is not being read and an exception is thrown... :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在访问值之前检查 dr.Read():
You should check for dr.Read() before accessing the values:
您必须循环遍历您的阅读器:
或
if(dr.Read())
如果您只有一个结果并且
你应该总是用 using: 包围你的 Reader
并且你应该在调用 ToString(); 之前做一些空检查。
这里有一个在代码中逐字编写查询的小技巧:
You must loop trough your reader:
or
if(dr.Read())
if you only have one resultAnd
You should always surround you Reader with a using:
And you should do some null check before you call ToString();
And here's a little tip to write queries in code, use verbatim: