错误 - “不存在数据时读取尝试无效."使用 SQLDataReader 时,即使数据存在 [英] Error - "Invalid attempt to read when no data is present." while using SQLDataReader even if data is present

查看:45
本文介绍了错误 - “不存在数据时读取尝试无效."使用 SQLDataReader 时,即使数据存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我收到此错误消息当没有数据存在时读取尝试无效"时,我试图对数据读取器使用参数化查询.

I was trying to to use parameterized query with data reader when I get this error message "Invalid attempt to read when no data is present."

但数据就是读者!

以下是执行此任务的代码行

Following is the line of code which performs this task

using (ConnectionManager connectionManager = new ConnectionManager())
{   
    string query = @"SELECT * FROM LoginTab WHERE username=@username " +
              "AND password=@password";

    List<SqlParameter> sqlParameterCollection = new List<SqlParameter>();
    sqlParameterCollection.Add(new SqlParameter("@username", SqlDbType.NVarChar) { Value = userName });
    sqlParameterCollection.Add(new SqlParameter("@password", SqlDbType.NVarChar) { Value = password });

    SqlDataReader sqlDataReader = connectionManager.ExecuteReader(query, CommandType.Text, sqlParameterCollection);

    String roles = sqlDataReader[0].ToString();
    return roles;
}

ExecuteReader 函数在另一个类中定义.

ExecuteReader function is defined in another class.

public SqlDataReader ExecuteReader(String strcmd, CommandType type, List<SqlParameter> Parametercollections)
{
    connnection = new SqlConnection(Connnectionstring);
    command = new SqlCommand(strcmd, connnection);
    command.CommandType = type;
    foreach (SqlParameter paras in Parametercollections)
    {
        command.Parameters.Add(paras);
    }
    try
    {
        connnection.Open();
        reader = command.ExecuteReader();
    }
    catch (SqlException E)
    {

    }
    finally
    {

    }

    return reader;
}

这里有什么问题?

推荐答案

当你调用 SqlCommand.ExecuteReader() 时,它给你的 SqlDataReader 最初被定位 before 第一条记录.在尝试访问任何数据之前,您必须调用 SqlDataReader.Read() 以移动到第一条记录.SqlDataReader.Read() 返回 true 如果它能够移动到第一条记录;如果没有记录,则返回 false.

When you call SqlCommand.ExecuteReader(), the SqlDataReader that it gives you is initially positioned before the first record. You must call SqlDataReader.Read() to move to the first record before attempting to access any data. SqlDataReader.Read() returns true if it was able to move to the first record; it returns false if there are no records.

if (sqlDataReader.Read())
{    
    String roles = sqlDataReader[0].ToString();
    return roles;
}
else
{
    // The user name or password is incorrect; return something else or throw an exception.
}

这篇关于错误 - “不存在数据时读取尝试无效."使用 SQLDataReader 时,即使数据存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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