在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);
}
1条答案
按热度按时间jtw3ybtb1#
正如@DAI评论的那样,IndexOutOfRangeException问题已经解决,这是因为SELECT查询没有得到正确的列。
SQL查询(待定)