当没有数据存在时,Sqldatareader'无效尝试读取' [英] Sqldatareader 'invalid attempt to read when no data is present'

查看:88
本文介绍了当没有数据存在时,Sqldatareader'无效尝试读取'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Invalid attempt to read when no data is present





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



< b>我尝试过:



"

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'无效尝试读取'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆