C# 如何安全地将可为空的结果从sqlreader强制转换为int?
我有一个包含空值的表,我需要使用SqlDataReader从表中获取数据。我不知道如何安全地将DBNull强制转换为int 我现在是这样做的:C# 如何安全地将可为空的结果从sqlreader强制转换为int?,c#,asp.net,null,sqldatareader,dbnull,C#,Asp.net,Null,Sqldatareader,Dbnull,我有一个包含空值的表,我需要使用SqlDataReader从表中获取数据。我不知道如何安全地将DBNull强制转换为int 我现在是这样做的: ... reader = command.ExecuteReader(); while (reader.Read()) { int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0; ... } ... 但
...
reader = command.ExecuteReader();
while (reader.Read()) {
int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
...
但是获取对象不能从DBNull强制转换为其他类型。
当PublicationYear为null时
如何安全地获取该值
谢谢。您应该将
reader[“PublicationYear”]
与DBNull进行比较。Value
,而不是null
DBNull
与null
不同。您应该尝试以下方法:
int y = (reader["PublicationYear"] != DBNull.Value) ? ...
这就是错误:(读卡器[“PublicationYear”]!=null)
您应该测试DBNull.Value
int ord = reader.GetOrdinal("PublicationYear");
int y = reader.IsDBNull(ord) ? 0 : reader.GetInt32(ord);
或者,或者:
object obj = reader["PublicationYear"];
int y = Convert.IsDBNull(obj) ? 0 : (int)obj;
将测试从
(读卡器[“PublicationYear”]!=null)
更改为(读卡器[“PublicationYear”]!=DBNull.Value)
更改
reader[“PublicationYear”]!=空
到
reader[“PublicationYear”]!=DBNull.Value
您应该明确检查返回的值是否属于类型DBNull
while (reader.Read()) {
int y = (!reader["PublicationYear"] is DBNull) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
事实上,您可以按值和类型进行比较:
reader["PublicationYear"] != DBNull.Value
简言之,您可以期望从数据库中为null返回DBNull
,而不是为null本身。应将数据库null值与DBNull.Value进行比较
reader=command.ExecuteReader();
while(reader.Read()){
int y=(读卡器[“PublicationYear”]!=DBNull.Value)?将.Convert.ToInt32(读卡器[“PublicationYear”]):0;
...
}
作为替代方案,您可以执行以下操作。
在将DBNull转换为0时,请更改执行select的过程。因此,select本身为空值返回零
演示该想法的片段
SELECT ...
,ISNULL (PublicationYear, 0) as PublicationYear
...
FROM sometable
这样做的好处是,代码中不需要额外的检查