问题
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