我正在开发我的第一个 ASP.Net 应用程序,似乎遇到了很多障碍(背景主要是 WinForms,最近有一个 MVC5 项目)。
我正在使用 OracleCommand
成功建立我的数据库连接并执行我的查询,但是当我尝试读取行时,我在第二个上得到了一个 Column contains NULL value
odr.GetDecimal(1)
的行。有人知道在读取 OracleDataReader 时如何处理空值吗?
下面是我的代码:
List<YearsOfService> yearsOfService = new List<YearsOfService>();
string SQL = "SELECT SCHOOL_YEAR as YEAR, " +
"TOTAL_SERVICE_CREDIT as ServiceCredited, " +
"RETIREMENT_SALARY as Salary, " +
"SOURCE_VALUE as CoveredEmployer " +
"FROM " + Schema + ".RANDOM_ORACLE_TABLE a " +
"WHERE MEMBER_ACCOUNT_ID = :memberAccountId";
DbConnection dbc = new DbConnection();
OracleCommand cmd = dbc.GetCommand(SQL);
cmd.Parameters.Add(new OracleParameter("memberAccountId", memberAccountId));
OracleDataReader odr = cmd.ExecuteReader();
int counter = 0;
if (odr.HasRows)
{
while (odr.Read())
{
YearsOfService yos = new YearsOfService();
yos.Year = odr.GetInt16(0);
yos.ServiceCredited = odr.GetDecimal(1); // Error on Second Pass
yos.Salary = odr.GetDecimal(2);
yos.CoveredEmployer = odr.GetString(3);
yearsOfService.Add(yos);
counter++;
}
}
return yearsOfService;
}
我原以为对 NULL 进行简单检查,如果是这样,用 0 替换(因为期望 Decimal
值)将适用于以下内容,但运气不佳。同样的错误:yos.ServiceCredited = Convert.IsDBNull(odr.GetDecimal(1)) ? 0 : odr.GetDecimal(1);
.
完整的错误是:
Oracle.DataAccess.dll 中出现类型为“System.InvalidCastException”的异常,但未在用户代码中处理
附加信息:列包含 NULL 数据
我已确认返回的 2 行格式如下:
Year|CreditedService|Salary |CoveredEmployer
2013|0.70128 |34949.66|ER
2014|NULL | 2213.99|NULL
有人对如何最好地进行提供建议吗?在读取 OracleDataReader 时,我应该如何处理接收到的 NULL 值?
最佳答案
yos.ServiceCredited = odr.IsDBNull(1) ? 0 : odr.GetDecimal(1);
OracleDataReader
提供了一个IsDBNull()
方法。
以及 GetDecimal()
上的文档要求我们这样做
Call IsDBNull to check for null values before calling this method.
关于c# - 通过 OracleDataReader 读取时处理 NULL 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26024722/