日期:2012-12-23  浏览次数:20351 次

 

可能平时我们在用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 = ""