0

同じテーブルを次々とチェックする2つの関数があります。この設定は非効率的なようです。これらを組み合わせる方法はありますか?

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

これを試して

新しいCustomerクラス(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
于 2012-12-20T04:02:47.313 に答える