Hello,
I use OleDbCommand object to make Insert, Update and Delete statements in SQL Server database but I don't destroy that <b>OleDbCommand object</b> and I wish to know what is the most optimal procedure to destroy it?
I have 3 choices:
<big>- DISPOSE in Finally section...</big>
<small>Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
sql = "Your SQL Statement Here"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
cmd = New OleDbCommand(sql, cnn)
cmd.ExecuteNonQuery()
MsgBox(" ExecuteNonQuery in OleDbConnection executed !!")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
Se debe hacer esto (ver texto en la sección Finally)…
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
sql = "Your SQL Statement Here"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
cmd = New OleDbCommand(sql, cnn)
cmd.ExecuteNonQuery()
MsgBox(" ExecuteNonQuery in OleDbConnection executed !!")
Catch ex As Exception
MsgBox("Can not open connection ! ")
Finally
<b>cmd.Dispose()
cnn.Close()
cmd = nothing</b>
End Try
End Sub
End Class</small>
- USING statement
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim connetionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
<b>Using</b> cnn As New OleDbConnection(connetionString)
cnn.Open()
Dim sql As String = "Your SQL Statement Here"
Dim cmd As New OleDbCommand(sql, cnn)
cmd.ExecuteNonQuery()
MsgBox(" ExecuteNonQuery in OleDbConnection executed !!")
<b>End Using</b>
Catch ex As Exception
MsgBox("Can not open connection ! " + ex.Message)
End Try
End Sub
- Implement the Dispose Finalize Pattern</big>, check this http://msdn.microsoft.com/en-us/library/s9bwddyx(v=vs.80).aspx
Thanks
Note: I use vs 2005 and VB.Net