vb.net检查数据库值是否为null

时间:2016-05-13 20:03:38

标签: mysql sql vb.net

我在vb.net中运行查询,我想测试列是否为null。我试过了:

If reader.GetString(2) IsNot Nothing Then

If IsDBNull(reader.GetString(2)) Then

If reader.GetString(2) IsNot NULL Then

If NOT reader.GetString(2) IS Nothing Then

If NOT reader.GetString(2) IS NULL Then

但他们都回来了:

Data is Null. This method or property cannot be called on Null values.

当我在MySQL中运行查询时,列显示NULL

2 个答案:

答案 0 :(得分:4)

问题是d1 <- structure(list(Date = structure(c(16801, 16802, 16802, 16802, 16803, 16803, 16806, 16806, 16806, 16808, 16808, 16814, 16814, 16816, 16817, 16817, 16817, 16824, 16824, 16825, 16825, 16826, 16829, 16829, 16829, 16829), class = "Date")), .Names = "Date", row.names = c(NA, 26L), class = "data.frame") 方法在内部将行值转换为字符串。如果行值为null,则会出现异常。

修复程序使用VB.NET三元运算符

GetString

或者如果您不希望在第三个字段为空时指定默认值,则只需编写

即可
Dim result = IF(reader.IsDbNull(2), "", reader.GetString(2))

答案 1 :(得分:0)

仅供将来参考:

您可以通过多种方法检查db值是否为空。
这里的示例包含完整的命名空间。

Dim reader As System.Data.SqlClient.SqlDataReader
Dim fieldIndex As Integer = 0

' reader(fieldIndex) is equivalent to reader.Item(fieldIndex)
Dim fieldValue As Object = reader.Item(fieldIndex)

Dim isFieldValueNull As Boolean

' Namespace: System.Data.SqlClient; Class: SqlDataReader
isFieldValueNull = reader.IsDBNull(fieldIndex)

' Namespace: Microsoft.VisualBasic; Module: Information
isFieldValueNull = Microsoft.VisualBasic.IsDBNull(fieldValue)

' Namespace: System; Class: Convert
isFieldValueNull = System.Convert.IsDBNull(fieldValue)

' Namespace: System; Class: DBNull
isFieldValueNull = System.DBNull.Value.Equals(fieldValue)

注意:DBNull.Value的实例始终为DBNull,因此永远不会Nothing

如果您想检查数据库值是否为null,则可以在方法调用之前放置Not关键字。

Dim isFieldValueNotNull As Boolean

isFieldValueNotNull = Not reader.IsDBNull(fieldIndex)
isFieldValueNotNull = Not Microsoft.VisualBasic.IsDBNull(fieldValue)
isFieldValueNotNull = Not System.Convert.IsDBNull(fieldValue)
isFieldValueNotNull = Not System.DBNull.Value.Equals(fieldValue)