使用.net中的参数更新数据库

发布于 2024-12-02 23:43:41 字数 1514 浏览 3 评论 0原文

更推荐使用这两种方法中的哪一种来使用给定的查询字符串更新数据库:

选项 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

或者还有其他更好的方法吗?

Which one of these two ways would be more recommended to update a database with a given query string:

Option 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

Option 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

Or is there any other better way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮生面具三千个 2024-12-09 23:43:41

看起来您正在尝试创建一个可重用的 UpdateCommand,这一切都很好。除了不打开连接之外,我不确定您是否正在关闭连接(除非 command.Dispose 也关闭连接)。您最好将尽可能多的数据库连接移至 Sub 中 另外,

我不确定您从异常块中得到 Err. ,但我建议设计一种更好的方法来处理任何异常 - 也许将其记录在某个地方

。 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

You然后可以这样做:

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)  

It looks like you're trying to create a reusable UpdateCommand, which is all well and good. In addtion to not opening the connection, I'm not sure that you're closing the connection (unless the command.Dispose also closes the connection. You'd be better off to move as much of the db connectivity into the Sub as possible.

Also, I'm not sure where you're getting Err. from in your exception block, but I'd recommend designing a better way to handle any exceptions - perhaps log it somewhere.

Finally, make the Sub a Function and return a bool indicating success/failure:

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

You could then do this:

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)

This example assumes sqlConnection is a class level variable holding your connection string. You could also read it directly from the config file if desired.

If you don't have any parameters for the command, you'll need to pass in an empty array (or modify the code in the function to check for params = Nothing):

Dim params As SqlParameter()
Dim Updated As Boolean = UpdateDatabase(query, params)  
往事随风而去 2024-12-09 23:43:41

由于与数据库访问无关的一个主要原因,这些都没有任何好处......

您正在吞噬所有托管异常。仅在可以适当处理异常的情况下才处理异常,几乎不需要接受异常并将其转换为返回值。在我看来,如果你这样做,那就不再是特殊情况了。

我不太记得 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

Neither of those are any good for one main reason that has nothing to do with database access...

You are swallowing any and all managed exceptions. Only handle exceptions if you can handle them appropriately, there is hardly ever a need to take an exception and translate it into return values. In my opinion if you do this, it's not longer an exceptional circumstance.

I can't quite remember the VB.NET Using syntax so I can't as yet provide another example. I'd also not use Call, I don't think it's required.

Sort of pseudo-code:

Using Dim command As New SqlCommand("INSERT...", conn)
    command.Parameters.AddWithValue()
    ....

    command.ExecuteNonQuery() // No need to call dispose, Using does that.
End Using
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文