I've already checked here.
I am looping an opening a connection each time and I'm not sure if ASP.NET handles it with a performance hit or that it recognizes this code and optimizes it automatically. What I have now:
For i As Integer = 0 To 100
cmd = New SqlCommand("UPDATE <table> where id=@id", myConnection)
cmd.Parameters.Add(New SqlParameter("@id", i))
Try
myConnection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
myConnection.Close()
End Try
Next i
How could I alter this code so that it does not open a connection each time? Bring the closing and opening outside the For
loop? Do a check on the existence of an open connection within the loop?
I'd love to see the code sample for the best practice.
Copyright Notice:Content Author:「Adam」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41818661/best-way-to-handle-connection-open-and-close-with-a-for-loop