2012-12-20 101 views
0

我有兩個函數檢查同一個表,一個接一個地查看。這種設置似乎效率低下。有沒有辦法將這些結合起來?如何將多個VB函數/ SQL查找合併爲一個vb.net函數

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 

回答

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 
+0

謝謝,我會試一試,非常感謝提及參數位。呃,不敢相信我錯過了那個。 – christopherdan

相關問題