你好,我目前正在使用以下方法获取SQL Server数据库的列:
public IDataReader myReader()
{
DbCommand = new SqlCommand("Select * from Mydatabase");
SqlConnection con = new SqlConnection(connectionstr);
con.Open();
DbCommand.Connection = con
return command.ExecuteReader(CommandBehavior.closeConnection);
}
IDataReader reader = myReader();
while (reader.Read())
{
int? a = (int?)reader["myIntColumn"];
}
在其他位置(对于其他表),代码工作正常,对于这个表也是如此,直到我处理数据库中的整数字段时。 然后我得到了System.InvalidCastException(在其他表中我没有遇到这个问题)。
我做错了什么吗?还是我需要做些什么才能使它工作? (问题中的int值在数据库中为NULL)
DbNull.Value
不是int?
类型,当你尝试使用as
进行强制类型转换时,如果无法转换该值,则它将为null。 - Patrick Hofmanas
进行转换时,不可能出现此错误消息。还有其他字段吗?另外,请尝试对您的代码进行分解:将所有值初始化到单独的变量中。这将使问题的诊断更加容易。 - Patrick Hofman