2012-08-30 187 views
0

我有一個簡單的功能,從數據庫基於這樣(簡體版)內嵌SQL語句返回單個列的數據:函數返回類型

Function GetId(ByVal name As String) As Object 

    Dim sql As String = "Select Id From table where username = '" & name & "'" 

    Using cmd As New SqlCommand 
     cmd.Connection = conn 
     cmd.CommandType = CommandType.Text 
     cmd.CommandText = sql 
     GetId = cmd.ExecuteScalar 
    End Using 

End Function 

如果SQL返回一行,也可以是NULL或整數,或者SQL不返回任何內容。

在代碼的另一部分,我有:

Dim userId As Object = New Object 

userId = GetBillingGroupToInvoice(name) 

是否確定使用對象這裏返回類型。如果不是,我應該指定什麼作爲這個函數的返回類型?這是在VB中,但在C#中的答案也可以。

感謝

回答

2

你的功能可能應該返回一個nullable integer,返回Nothing當你的SQL服務器返回任何內容或DBNull(如果你不想做之間的差異沒有行返回的DBNull)。

Function GetId(ByVal name As String) As Integer? 

    Dim sql As String = "Select Id From table where username = '" & name & "'" 

    Using cmd As New SqlCommand 
     cmd.Connection = conn 
     cmd.CommandType = CommandType.Text 
     cmd.CommandText = sql 
     Dim result = cmd.ExecuteScalar 
     Return If(DBNull.Value.Equals(result), 
        Nothing, 
        DirectCast(result, Integer?)) 
    End Using 

End Function 

然後,你就打電話給你的方法是這樣的:

Dim userId = GetBillingGroupToInvoice(name) 
If userId.HasValue Then 
    'Do something with userId.Value' 
End If 
1

如果SQL查詢返回一個整數或者一個空值,你可能希望你的函數返回一個可空INT(int?在C#中),而不是對象,增加類型安全。

1

從ExecuteScalar轉換爲整型返回類型(如果不是DBNull)。你可以返回可空類型int(int?在C#中)。

1

您應該指定Integer返回類型而不是Object

Function GetId(ByVal name As String) As Integer 
    Dim sql As String = "Select Id From table where [email protected]" 
    Dim retValue as Integer = -1 
    Using cmd As New SqlCommand 
     cmd.Connection = conn 
     cmd.CommandType = CommandType.Text 
     cmd.CommandText = sql 
     cmd.Parameters.Add("@name",SqlDbType.VarChar,30).Value=name 
     Dim result = cmd.ExecuteScalar() 
     if Not IsNothing(result) And Not IsDBNull(result) Then 
      retValue=CType(result,Integer) 
     End If 
    End Using 
    return retValue 
End Function 
+0

謝謝,但如果列是NULL從類型得到轉換「爲DBNull」鍵入「整數」是無效的。與此錯誤。 – 03Usr