2012-02-27 158 views
1

此代碼有效。它基於我在互聯網上找到的一些代碼。尋找使用ExecuteScalar的最佳方式()

你能告訴我,如果編碼是獲得標量值的最佳方法,並且如果有更好的方法可以顯示編碼樣本嗎?

Dim objParentNameFound As Object 

TextBoxParentsName.Text = "" 

If TextBoxParentID.Text <> "" Then 

    ' Display the parent's name using the parent ID. ' 
    Dim strSqlStatement As String = "Select FatherName " & _ 
             "From Parents " & _ 
            "Where ID = @SearchValue" 

    ' Set up the sql command and lookup the parent. ' 
    Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection) 

     With objSqlCommand 

      ' Add SqlParameters to the SqlCommand. ' 
      .Parameters.Clear() 
      .Parameters.AddWithValue("@SearchValue", TextBoxParentID.Text) 

      ' Open the SqlConnection before executing the query. ' 
      Try 
       ObjConnection.Open() 

       Try 
        objParentNameFound = .ExecuteScalar() 
        If objParentNameFound <> Nothing Then 

         ' Display the parent name here. ' 
         TextBoxParentsName.Text = objParentNameFound 
        End If 

       Catch exSqlErrors As SqlException 
        MessageBox.Show("Sorry, I couldn't execute your query because of this error: " & _ 
            vbCrLf & vbCrLf & exSqlErrors.Message, _ 
            "Error") 
       End Try 
      Catch exErrors As Exception 

       MessageBox.Show("Sorry, there was an error. Details follow: " & _ 
           vbCrLf & vbCrLf & exErrors.Message, _ 
           "Error") 
      Finally 
       ObjConnection.Close() 
      End Try 
     End With 
    End Using 
End If 

回答

2

Microsoft Access Application塊有一些如何使用ADO.Net的很好的例子。特別是,您可能會發現有幫助的是,他們如何將諸如ExecuteScalar()之類的任務組織爲一系列重載方法,從而輕鬆調用所需的過程。 您發佈的樣本將大大有益於將問題分離出來。換句話說,拿你使用的代碼來建立連接,命令和參數,並使其成爲一個單獨的方法。這允許代碼被重複使用,而不會複製&粘貼到您的代碼庫中。這允許您的調用代碼只需傳入參數並將結果綁定到文本框或其他控件。

編輯:例 假設你使用SqlHelper.vb類,你可以這樣做以下:

Dim searchValue As Integer = 1 
Dim myConnectionString As String = "MyConnectionString" 
Dim sqlStatement As String = "SELECT FatherName FROM Parents WHERE ID = @SearchValue" 
Dim paramList(0) As SqlParameter 
paramList(0) = New SqlParameter() With {.Value = searchValue, .ParameterName = "@SearchValue"} 

TextBoxParentsName.Text = SqlHelper.ExecuteScalar(myConnectionString, CommandType.Text, sqlStatement, paramList).ToString() 
+0

感謝您的答覆。我會看看Microsoft Access應用程序,看看我是否可以從中學習。如果你有時間,你能展示一些代碼塊來幫助進一步擴展將代碼分離到其他方法嗎? – 2012-02-27 14:48:50