SQLDataReader:处理空值
我正在处理的一些表有空值并且抛出错误。到目前为止,我尝试了一些解决方案来处理空值,但没有成功。
以下是我迄今为止所做的工作的代码示例;
If (r("datemodified").Equals(DBNull.Value)) Then
datemodified = String.Empty
Else
datemodified = (r("datemodified"))
End If
和;
If r.HasRows Then
datemodified = (r("datemodified"))
Else
datemodified = String.Empty
End If
和;
If r("datemodified") = Nothing Then
datemodified = String.Empty
Else
datemodified = (r("datemodified"))
End If
和;
If r.IsDBNull("datemodified") Then
datemodified = String.Empty
Else
datemodified = (r("datemodified"))
并通过sql;
Select isnull(datemodified, '')
最终结果是 IndexOutOfRangeException。
这是sql;
select datemodified, maintainedby, email, hitcount from grouping where id = @footid
ps,我已经运行了查询并且运行正常(即所有列都存在)
Some tables I am dealing with have null values and are throwing errors. So far ive tried a few solutions to deal with the nulls with no success.
Here are the code samples from my efforts so far;
If (r("datemodified").Equals(DBNull.Value)) Then
datemodified = String.Empty
Else
datemodified = (r("datemodified"))
End If
and;
If r.HasRows Then
datemodified = (r("datemodified"))
Else
datemodified = String.Empty
End If
and;
If r("datemodified") = Nothing Then
datemodified = String.Empty
Else
datemodified = (r("datemodified"))
End If
and;
If r.IsDBNull("datemodified") Then
datemodified = String.Empty
Else
datemodified = (r("datemodified"))
and via sql;
Select isnull(datemodified, '')
The end result is an IndexOutOfRangeException.
here is the sql;
select datemodified, maintainedby, email, hitcount from grouping where id = @footid
ps, i have ran the query and it is working ok (i.e all the cols exist)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要处理代码中的空值,您可以使用 IsDBNull 方法:
要处理 SQL 中的空值,您必须为字段指定一个名称,以便能够在数据读取器中通过名称访问它:
To handle the null value in the code you can use the IsDBNull method:
To handle the null value in the SQL you have to give the field a name, to be able to access it by name in the data reader:
IndexOutofRangeException 是因为您尝试访问的列在结果集中不存在。
当您通过 SqlDataReader 访问序数或列时,必须指定列索引或列名称。在您的场景中,您需要为返回的 SQL 列指定别名。
The IndexOutofRangeException is becoz of the Column you are trying to access does not exists in the result set.
When you are accessing the Ordinal, or the Column via SqlDataReader, you must specify the Column Index, or the Column Name. In your scenario, you need to specify an Alias for the SQL Column returning.