当没有数据存在时,Sqldatareader'无效尝试读取'

编程入门 行业动态 更新时间:2024-10-28 20:31:04
本文介绍了当没有数据存在时,Sqldatareader'无效尝试读取'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在asp项目中使用Visual Studio 2015企业版,其中我收到错误

I am using Visual Studio 2015 Enterprise edition for asp project in which i am getting error "

Invalid attempt to read when no data is present

实际上SqlDataReader正在执行命令但我得到这个错误可以有人解释我哪里错了 我尝试过:

" Actually the SqlDataReader is executing the command but i am getting this error can anyone explain me where is the wrong What I have tried:

con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); if (con.State == ConnectionState.Closed) con.Open(); string str = "select RoleName from tblRoles"; cmd = new SqlCommand(str, con); sdr = cmd.ExecuteReader(); string roleName = sdr["RoleName"].ToString();

我收到错误最后一行说'无数据存在时读取无效'

I am getting error at the last line saying 'Invalid attempt to read when no data is present'

推荐答案

要使用DataReader,您必须告诉它一次读取每一行: To use a DataReader, you have to tell it to read each line at a time: using (SqlConnection con = new SqlConnection(strConnect)) { con.Open(); using (SqlCommand cmd = new SqlCommand("SELECT RoleName FROM tblRoles", con)) { using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string roleName = (string) reader["RoleName"]; Console.WriteLine(roleName); } } } }

更多推荐

当没有数据存在时,Sqldatareader'无效尝试读取'

本文发布于:2023-10-30 22:13:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Sqldatareader

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!