如何将多个VB函数/ SQL查找组合到一个vb.net函数中

时间:2012-12-20 03:49:42

标签: vb.net sql-server-2008 return-value

我有两个功能可以检查同一个表,一个接一个地检查。这种设置似乎效率低下。有没有办法将这些结合起来?

getCustomerName(customerID)
getCustomerEmail(customerID)

'GET CUSTOMER NAME 
Public Shared function getCustomerName(myArg) as String
Dim objConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionString"))
Dim finalCustomerName as string
objConnection.Open()
    Dim objCommand As New SqlCommand("SELECT customerName FROM customers WHERE customerID = '" + MyArg + "'", objConnection)
    Dim objDataReader as SqlDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
    While objDataReader.Read()
        finalCustomerName = objDataReader("customerName")
    End While
objConnection.Close()
Return finalCustomerName
End function

'GET CUSTOMER EMAIL
Public Shared function getCustomerEmail(myArg) as String
Dim objConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionString"))
Dim finalCustomerEmail as string
objConnection.Open()
    Dim objCommand As New SqlCommand("SELECT customerEmail FROM customers WHERE customerID = '" + MyArg + "'", objConnection)
    Dim objDataReader as SqlDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
    While objDataReader.Read()
        finalCustomerEmail = objDataReader("customerEmail")
    End While
objConnection.Close()
Return finalCustomerEmail
End function

1 个答案:

答案 0 :(得分:0)

试试这个

新的Customer类(您可​​以添加更多与客户相关的属性并从以下函数返回它们):

Public Class Customer

    Public Property CustomerName() As String
        Get
            Return m_CustomerName
        End Get
        Set
            m_CustomerName = Value
        End Set
    End Property
    Private m_CustomerName As String
    Public Property CustomerEmail() As String
        Get
            Return m_CustomerEmail
        End Get
        Set
            m_CustomerEmail = Value
        End Set
    End Property
    Private m_CustomerEmail As String
End Class

你的功能应该是

// your function to get customer details
Public function getCustomer(myArg) as Customer
Dim custobj as New Customer()

Dim objCommand As New SqlCommand("SELECT customerEmail,CustomerName FROM customers WHERE customerID = @custid", objConnection)

objCommand.Parameters.AddWithValue("@custid",myArg) //use parameters to avoid sql injections

Dim objDataReader as SqlDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
While objDataReader.Read()
    custobj.CustomerName = objDataReader("customerName")
    custobj.CustomerEmail = objDataReader("customerEmail")
End While
objDataReader.Close()
objConnection.Close()

Return custObj
End function