寻找使用的ExecuteScalar的最佳方式()(Looking for the best way

2019-09-28 01:36发布

This code works. It's based on some code I found on the internet.

Can you tell me if the coding is the best way to get a scalar value and if there is a better way can you show coding samples?

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 

Answer 1:

在Microsoft Access应用程序块有如何使用ADO.Net一些很好的例子。 尤其是你可能会发现有用的是他们如何组织的任务,如ExecuteScalar()为使其易于调用您需要的作业的一系列的重载方法。 您发布的样品将从分离出的担忧大大受益。 换句话说,带你用它来建立连接,命令和参数,并做出一个单独的方法或方法的代码。 由此,不复制和整个你的代码粘贴到可重复使用的代码。 这使您的调用代码简单地在参数(S)通过,并将结果结合到你的文本框或其他控件。

编辑:举例假设你使用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()


文章来源: Looking for the best way to use ExecuteScalar()