Open SqlConnection being passed as a parameter?

筅森魡賤 提交于 2019-12-12 03:49:04

问题


I ran across this bit of code (not mine) and it weirded me out a little bit.

Public Overridable Function Save(ByVal UpdateUserID As Integer) As Integer
    Dim conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("mcle").ToString())

    Try
        conn.Open()
        Return Save(conn, UpdateUserID)
    Finally
        conn.Close()
    End Try
End Function

Public Overridable Function Save(ByVal conn As SqlConnection, ByVal UpdateUserID As Integer) As Integer
    If Me.activityID <> 0 Then
        Return SaveAct(conn, UpdateUserID)
    Else
        Return AddAct(conn, UpdateUserID)
    End If
End Function

(For reference, SaveAct and AddAct are both long functions that add a bunch of parameters and update the database)

Now, is it kosher to pass the open connection as a parameter or could this lead to problems? Not breaking so far, just wondering what the best practice is here.

Thanks in advance.


回答1:


Passing an open connection is perfectly okay to do... though normally I'd invert that and use a function that returns an open and ready connection into the existing function. So it might look something like this:

Public Overridable Function Save(ByVal UpdateUserID As Integer) As Integer
    Using cn As SqlConnection = GetConnection()
        If Me.activityID <> 0 Then
            Return SaveAct(conn, UpdateUserID)
        Else
            Return AddAct(conn, UpdateUserID)
        End If
    End Using
End Function

This code would be part of a data access layer, such that only certain methods/classes can see the GetConnection() method.



来源:https://stackoverflow.com/questions/12644849/open-sqlconnection-being-passed-as-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!