可能平时我们在用vb写程序的过程中,会忽视一些面向对象的思想。希望通过一个例子能够对大家起到抛砖引玉的作用,我们举一个vb访问数据库的例子。这是本人第一次写技术方面的文章,请大家支持!!qq:16644686
1。经常出现的写法
在vb中实现对数据库的访问,我们可能会通过一个全局函数来实现,例如以下的代码:
public function dbsqlopen(strname as string, strpwd as string, _
strip as string, strdatabase as string) as adodb.connection
'purpose: 连接sql数据库
'accepts:
' strname-------登陆服务器用户名
' strpwd--------登陆服务器密码
' strip---------服务器地址
' strdatabase---数据库名
'return: 连接对象
dim madocon as adodb.connection '///////////////////////////////
set madocon = new adodb.connection
madocon.connectionstring = "provider=sqloledb.1;persist security info=false;user id=" _
& strname & ";pwd=" & strpwd & ";initial catalog=" & strdatabase & ";data source=" & strip & ""
madocon.open
set dbsqlopen = madocon
end function
然后在其它地方要用到ado连接的时候就通过该函数来返回。比如:
private sub form_load()
set rs = new adodb.recordset
rs.cursortype = adopenkeyset
rs.locktype = adlockpessimistic
rs.activeconnection = dbsqlopen(strlocalname, strlocalpwd, "(local)", strlocaldb)
........
end sub
程序中如果采用这种方式来实现连接数据库,效率非常的低下。你每用到一次dbsqlopen这个全局函数,全局函数里面声明的adodb.connection就会open一次,假如你的程序频繁调用这个全局函数,可想而之程序的效率将会多么的低下。如何避免这种设计方式呢?我们采用下面的方式。
2.改进的写法
假如我们设计一个类来实现数据库访问就会避免这样的问题。具体代码如下:
private m_adoconn as new adodb.connection
private m_adorecordset as new adodb.recordset
public function dbinit()
set m_adoconn = nothing
set m_adorecordset = nothing
end function
public function dbend()
m_adorecordset.close
m_adoconn.close
set m_adorecordset = nothing
set m_conn = nothing
end function
public function dbsqlopen(strname as string, strpwd as string, _
strip as string, strdatabase as string)
m_adoconn.connectionstring = "provider=sqloledb.1;persist security info=false;user id=" _
& strname & ";pwd=" & strpwd & ";initial catalog=" & strdatabase & ";data source=" & strip & ""
m_adoconn.connectiontimeout = 5
m_adoconn.open
end function
public function dbgetconn() as adodb.connection
dbgetconn = m_adoconn
end function
我们在模块里面可以声明一个public m_dbclass as dbclass来实现对数据库的访问。
private sub command1_click()
dim rs1 as adodb.recordset
rs1.activeconnection = m_dbclass.dbgetconn
end sub
private sub form_load()
dim strname as string
dim strpwd as string
dim strip as string
dim strdatabase as string
strname = "sa"
strpwd = ""
strip = "192.168.0.37"
strdatabase = ""
m_dbclass.dbinit
m_dbclass.dbsqlopen strname, strpwd, strip, strdatabase
end sub
private sub form_unload(cancel as integer)
m_dbclass.dbend
end sub
每一次要用到数据库连接的时候我们就通过类里面的dbgetconn方法来返回一个adodb.connection。
新闻热点
疑难解答