0

我有两个检查同一张表的函数,一个接一个。这种设置似乎效率低下。有没有办法将这些结合起来?

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
4

1 回答 1

0

尝试这个

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

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
于 2012-12-20T04:02:47.313 回答