2012-02-27 5 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 응용 프로그램을보고 배울 수 있는지 확인합니다. 시간이 있다면 코드를 다른 방법으로 분리하는 데 도움이되는 몇 가지 코드 블록을 보여줄 수 있습니까? –

관련 문제