2012-08-30 194 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