2016-05-13 87 views
-1

我在vb.net中運行查詢,我想測試列是否爲空。我曾嘗試:vb.net檢查數據庫值是否爲空

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

+0

'reader'null? – Cortright

回答

4

的問題是GetString方法內部投你行值賦給一個字符串。如果行值爲空,則會得到異常。

的修復程序使用VB.NET三元運算符

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

,或者如果你不想指定一個默認值時,第三場爲空,你可以簡單地寫

if Not reader.IsDbNull(2) Then 
    ....... 
End if 
+0

我可以使用IsNotNull嗎? – charlie

+0

抱歉,但不是?我對此並不熟悉。你在哪裏找到它? – Steve

+0

我沒有,這就是爲什麼我問。或者我應該'如果不reader.IsDBNull(2)那麼' – charlie

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

如果您想檢查數據庫值是否爲空,那麼您可以在方法調用之前放置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)