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。