本文介绍了当没有数据存在时,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'无效尝试读取'
发布评论