C#IDataReader System.IndexOutOfRangeException问题

6psbrbz9  于 2022-10-03  发布在  C#
关注(0)|答案(1)|浏览(155)

在C#中使用IDataReader时,我遇到了IndexOutOfRangeException问题。以下是我的样例代码。代码在执行GetDataValue的函数时抛出异常。

public List<Users> SelectUsersbyUsernamePassword(string username, string password)
    {
        const string SQL_STATEMENT =
            "SELECT U.Username, U.Password, U.Role " +
            "FROM Users U ";

        List<Users> listusers = new List<Users>();
        Database db = new Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase(CONNECTION_NAME);

        using (DbCommand cmd = db.GetSqlStringCommand(SQL_STATEMENT))
        {
            db.AddInParameter(cmd, "@username", DbType.String, username);
            db.AddInParameter(cmd, "@password", DbType.String, password);
            try
            {
                using (IDataReader dr = db.ExecuteReader(cmd))
                {
                    while (dr.Read())
                    {
                        Users users = new Users();
                        users.UserID = base.GetDataValue<int>(dr, "UserID");
                        users.Username = base.GetDataValue<string>(dr, "Username");
                        users.Password = base.GetDataValue<string>(dr, "Password");
                        users.Role = base.GetDataValue<string>(dr, "Role");

                        listusers.Add(users);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
                //throw new DbException(ex.Message, SQL_STATEMENT, "username = " + username, ex.InnerException);
            }
        }
        return listusers;
    }

数据访问

protected T GetDataValue<T>(IDataReader dr, string columnName)
    {
        int i = dr.GetOrdinal(columnName);

        if (!dr.IsDBNull(i))
            return (T)dr.GetValue(i);
        else
            return default(T);
    }
jtw3ybtb

jtw3ybtb1#

正如@DAI评论的那样,IndexOutOfRangeException问题已经解决,这是因为SELECT查询没有得到正确的列。

// Read values.
users.UserID = base.GetDataValue<int>(dr, "UserID");
users.Username = base.GetDataValue<string>(dr, "Username");
users.Password = base.GetDataValue<string>(dr, "Password");
users.Role = base.GetDataValue<string>(dr, "Role");

SQL查询(待定)

const string SQL_STATEMENT =
   "SELECT U.UserID, U.Username, U.Password, U.Role " +
   "FROM Users U " +

相关问题