更推荐使用以下两种方法中的哪一种来更新具有给定查询字符串的数据库:
选项1:
Dim query As String = "INSERT INTO employee VALUES (@Name, @Age)"
Dim command As New SqlClient.SqlCommand(query, sqlConnection)
Dim params As SqlParameter() = {
New SqlParameter("@Name", txtName.Value),
New SqlParameter("@Age", txtAge.Value))
}
Call UpdateDatabase(command, params, NumError, DescError)
Public Sub UpdateDatabase(ByVal command As SqlCommand, ByVal parameters() As SqlParameter, ByRef NumError As Double, ByRef DescError As String)
Try
For Each parameter In parameters
command.Parameters.Add(parameter)
Next
command.ExecuteNonQuery()
command.Dispose()
NumError = 0
DescError = ""
Catch ex As Exception
NumError = Err.Number
DescError = Err.Description
End Try
End Sub
选项2:
Dim query As String = "INSERT INTO employee VALUES (@Name, @Age)"
Dim command As New SqlClient.SqlCommand(query, sqlConnection)
command.Parameters.AddWithValue("@Name", txtName.Value)
command.Parameters.AddWithValue("@Age", txtAge.Value)
Call UpdateDatabase(command, NumError, DescError)
Public Sub UpdateDatabase(ByVal command As SqlCommand, ByRef NumError As Double, ByRef DescError As String)
Try
command.ExecuteNonQuery()
command.Dispose()
NumError = 0
DescError = ""
Catch ex As Exception
NumError = Err.Number
DescError = Err.Description
End Try
End Sub
或者还有其他更好的方法吗?
答案 0 :(得分:1)
对于与数据库访问无关的一个主要原因,这些都没有任何好处......
您正在吞下任何和所有托管异常。只有处理异常才能处理异常,几乎不需要异常并将其转换为返回值。在我看来,如果你这样做,它不再是一个例外情况。
我不太记得VB.NET Using
语法,所以我还不能提供另一个例子。我也不会使用Call
,我认为这不是必需的。
伪代码的排序:
Using Dim command As New SqlCommand("INSERT...", conn)
command.Parameters.AddWithValue()
....
command.ExecuteNonQuery() // No need to call dispose, Using does that.
End Using
答案 1 :(得分:1)
看起来你正在尝试创建一个可重用的UpdateCommand,这一切都很好。除了不打开连接之外,我不确定你是否正在关闭连接(除非command.Dispose也关闭连接。你最好尽可能多地将数据库连接移动到Sub中
另外,我不确定你在哪里得到Err。来自你的异常块,但我建议设计一种更好的方法来处理任何异常 - 也许记录在某个地方。
最后,使Sub成为一个函数并返回一个表示成功/失败的bool:
Public Function UpdateDatabase(ByVal sql As String, ByVal parameters() As SqlParameter) As Boolean
Dim Successful As Boolean = False
Try
Using conn As SqlConnection = new SqlConnection(sqlConnection)
Using command As New SqlCommand(sql, conn)
command.CommandType = CommandType.Text
For Each parameter As SqlParameter In parameters
command.Parameters.Add(parameter)
Next
conn.Open()
command.ExecuteNonQuery()
Successful = True
End Using
End Using
Catch ex As Exception
Successful = False
' Do something with the exception
End Try
End Function
然后你可以这样做:
Dim query As String = "INSERT INTO employee VALUES (@Name, @Age)"
Dim params As SqlParameter() = {
New SqlParameter("@Name", txtName.Value),
New SqlParameter("@Age", txtAge.Value))
}
Dim Updated As Boolean = UpdateDatabase(query, params)
此示例假定sqlConnection
是包含连接字符串的类级别变量。如果需要,您也可以直接从配置文件中读取它。
如果您没有该命令的任何参数,则需要传入一个空数组(或修改函数中的代码以检查params = Nothing):
Dim params As SqlParameter()
Dim Updated As Boolean = UpdateDatabase(query, params)