I'm using the code below to save a record in my database. I was thinking that I am creating new instances of the SQL Command object and fear that I might be bloating the system memory and not doing proper garbage collection for unused objects. Can anyone point out which parts of this code I can improve?
By the way, this is the first time I've used SQL Transactions.
Private Sub SaveRecord()
Dim type As Integer = 0
Try
Using dbConn As New SqlConnection(strConnStr)
Try
dbConn.Open()
_params = New List(Of SqlParameter)
' Register record
If formMode = 1 Then
dbCmd = dbConn.CreateCommand
dbTran = dbConn.BeginTransaction(IsolationLevel.ReadCommitted, "RBT")
If OrganismID = -1 Then
dbCmd = New SqlCommand("spNewZEntity", dbConn, dbTran)
dbCmd.CommandType = CommandType.StoredProcedure
AssignZEntityParam()
ZEntityID = dbCmd.ExecuteScalar
If ZEntityID = Nothing Then Throw New Exception("Failed to Generate ZEntityID")
End If
dbCmd = New SqlCommand("spNewXEntity", dbConn, dbTran)
dbCmd.CommandType = CommandType.StoredProcedure
AssignXEntityParam()
XEntityID = dbCmd.ExecuteScalar()
If XEntityID = Nothing Then Throw New Exception("Failed to Generate XEntityID")
For Each AZ In _AZItems
If AZ.IDAZ = -1 Then
dbCmd = New SqlCommand("spNewAZ", dbConn, dbTran)
dbCmd.CommandType = CommandType.StoredProcedure
_params.Clear()
dbCmd.Parameters.AddWithValue("@AZName", AZ.nameAZ)
AZID = dbCmd.ExecuteScalar()
If AZID = Nothing Then Throw New Exception("Failed to Generate AZID")
type = 1
Else
type = 2
End If
dbCmd = New SqlCommand("spNewISO", dbConn, dbTran)
dbCmd.CommandType = CommandType.StoredProcedure
AssignCreateISOParam(type, AZ)
dbCmd.ExecuteNonQuery()
Next
dbTran.Commit()
dbConn.Close()
MsgBox("Done.", MsgBoxStyle.Information)
End If
flagSaved = True
Dispose()
Catch ex As Exception
CreateLog("SaveRecord", ex.Message, ex)
Try
MsgBox("Attempting to rollback changes to database...", MsgBoxStyle.Information, emParsing)
If Not dbTran.Connection Is Nothing Then
dbTran.Rollback("RBT")
dbTran.Dispose()
MsgBox("Rollback successful.", MsgBoxStyle.Information, emParsing)
Else
MsgBox("Failed to rollback changes. Please contact your system administrator.",
MsgBoxStyle.Exclamation, emParsing)
End If
Catch ex2 As SqlException
CreateLog("SaveRecord/Rollback Failed", ex2.Message, ex2)
MsgBox("Failed to rollback changes. Please contact your system administrator.", MsgBoxStyle.Exclamation, "Rollback Failed")
End Try
Finally
dbCmd.Dispose()
End Try
End Using
Catch ex As Exception
CreateLog("SaveRecord", ex.Message, ex)
End Try
End Sub