sql - override Sub finalize to make sure connection to DataBase is closed -
i connecting access database , wondering if overriding sub finalize in cconnectiondb.vb useful:
imports system.data.sqlclient imports system.data.common imports system.io public class dbconn private datacon dbconnection private dbconnectionopen boolean = false protected overrides sub finalize() seek datacon.close() grab ex exception end seek end sub public sub opendatabaseconnection() seek datacon.open() grab ex exception throw new system.exception("error opening info connection.", ex.innerexception) dbconnectionopen = false exit sub end seek dbconnectionopen = true end sub public sub closedatabaseconnection() datacon.close() dbconnectionopen = false end sub ''' <summary> ''' creates new connection access database ''' </summary> ''' <param name="filename">the total path of access file</param> ''' <remarks></remarks> public sub new(byval filename string) 'provider=microsoft.ace.oledb.12.0;data source=c:\myfolder\myaccess2007file.accdb;persist security info=false; dim filedata fileinfo = my.computer.filesystem.getfileinfo(filename) datacon = new oledb.oledbconnection dim csb oledb.oledbconnectionstringbuilder = new oledb.oledbconnectionstringbuilder csb.connectionstring = "data source=" & filename select case filedata.extension.tolower case ".mdb" : csb.add("provider", "microsoft.jet.oledb.4.0") case ".accdb" : csb.add("provider", "microsoft.ace.oledb.12.0") end select datacon.connectionstring = csb.connectionstring seek datacon.open() datacon.close() grab ex exception throw new system.exception("unable connect database.", ex.innerexception) end seek end sub end class
that's not terribly useful. finalize
deconstructor won't called until garbage collector gets around destroying object. and, since dbconn
object thing has reference dbconnection
object, automatically destroy @ same time anyway. if want free connection done it, recommended method implement idisposable
interface in class. instance:
private class dbconn implements idisposable private datacon dbconnection private disposedvalue boolean protected overridable sub dispose(disposing boolean) if not me.disposedvalue if disposing seek datacon.close() grab ex exception end seek end if end if disposedvalue = true end sub public sub dispose() implements idisposable.dispose dispose(true) gc.suppressfinalize(me) end sub end class
however, if implement idisposable
, work isn't done there. dispose
method on idisposable
objects never gets called automatically. need tell object when done calling dispose method manually. alternatively, utilize using
block:
using d new dbconn ' dbconn.dispose method automatically gets called 1 time execution leaves using block end using
sql database vb.net visual-studio-2010
No comments:
Post a Comment