2012-02-27 12 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アプリケーションを見て、それから学ぶことができるかどうかを見ていきます。時間があれば、コードを他の方法に分離するためにいくつかのコードブロックを表示できますか? –

関連する問題