寻找使用ExecuteScalar()的最佳方法

时间:2012-02-27 14:14:48

标签: sql vb.net coding-style 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 

1 个答案:

答案 0 :(得分:3)

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()