问题描述
此代码工作。它基于我在互联网上找到的一些代码。
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
推荐答案
块有一些很好的示例如何使用ADO.Net。特别是你可能会觉得有帮助的是他们是如何组织任务,如 ExecuteScalar()
到一系列重载的方法,使它很容易调用所需的过程。
您发布的示例将极大地受益于分离出的问题。换句话说,拿你使用的代码来建立连接,命令和参数,并使其成为单独的方法或方法。这允许代码被重用而不需要复制&粘贴到你的代码库。这允许您的调用代码简单地传递参数,并将结果绑定到文本框或其他控件。
The Microsoft Access Application block has some nice examples of how to use ADO.Net. In particular what you might find helpful is how they've organized tasks such as ExecuteScalar()
into a series of overloaded methods making it easy to invoke the process you need.The sample you posted would greatly benefit from separating out the concerns. In other words, take the code you use to build up the connection, command and parameters and make that a separate method or methods. This allows the code to be reused without copy& pasting it throughout your codebase. This allows your calling code to simply pass in the parameter(s) and bind the result to your text box or other controls.
编辑:示例
假设你使用SqlHelper.vb类,你可以这样做:
ExampleAssuming you use the SqlHelper.vb class you can do something like the following:
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()
这篇关于寻找最好的方法使用ExecuteScalar()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!