首页 > 代码库 > VB6-操作数据库

VB6-操作数据库

 

平常搞数据库操作多了就想把经常用的内容放在一起,我也懒,在一本书里的工程例子挑了一个bas,修修改改,凑合这用吧。

 

 1 Public strCnn As String  数据库连接字符串 2 Public AdoCnn As ADODB.Connection 数据库连接 3 Public IsConnect As Boolean  判断是否连接 4  5  6 Private Sub Connect() 连接数据库 7     On Error GoTo Err: 8     If IsConnect = True Then  如果连接标记为真,则返回。否则会出错 9         Exit Sub10     End If11     12     Set AdoCnn = New ADODB.Connection 关键New用于创建新对象cnn13     With AdoCnn14         .ConnectionString = strCnn15         .ConnectionTimeout = 1016         .Open17     End With18     IsConnect = True  设置连接标记,表示已经连接到数据库19     Exit Sub20 Err:21     If Err = -2147467259 Then22         Set Cnn = Nothing23         MsgBox Err.Description & "请检查数据库配置!", vbOKOnly + vbInformation, "Connect"24     Else25         MsgBox Err.Description & "请检查数据库配置!", vbExclamation, "Connect"26     End If27     28 End Sub29 30 Public Sub Disconnect() 断开与数据库的连接31     Dim rc As Long32     If IsConnect = False Then Exit Sub 如果连接标记为假,标明已经断开连接,则直接返回33     AdoCnn.Close  关闭连接34     35     Set AdoCnn = Nothing36     IsConnect = False37 End Sub38 39 Public Sub DB_Connect() 使用Connect_Num控制数据库连接40     Connect_Num = Connect_Num + 141     Connect42 End Sub43 44 Public Sub DB_Disconnect()45     If Connect_Num >= CONNECT_LOOP_MAX Then46         Connect_Num = 047         Disconnect48     End If49 End Sub50 51 Public Sub DBapi_Disconnect() 强制关闭api方式访问的数据库,计数器复位52     Connect_Num = 053     Disconnect54 End Sub55 56 Public Sub ExecSql(ByVal TmpSql As String)   执行数据库操作语句57     On Error GoTo Err:58     Dim cmd As New ADODB.Command  创建Command对象cmd59     DB_Connect    连接到数据库60     Set cmd.ActiveConnection = AdoCnn  设置cmd的ActiveConnection属性,指定与其关联的数据库连接61     cmd.CommandText = TmpSql  设置要执行的命令文本62     cmd.Execute63     Set cmd = Nothing64     DB_Disconnect65     Exit Sub66 Err:67     MsgBox Err.Description, 64, "ExecSql"68 End Sub69 70 Public Function QuerySql(ByVal TmpSql As String) As ADODB.Recordset 执行数据库查询语句71     On Error GoTo Err:72     Dim rst As New ADODB.Recordset73     DB_Connect    连接到数据库74     If IsConnect = False Then Exit Function75     Set rst.ActiveConnection = AdoCnn    设置rst的ActiveConnection属性,指定与其关联的数据库连接76     rst.CursorType = adOpenKeyset77     rst.LockType = adLockOptimistic   设置锁定类型78     rst.Open TmpSql    打开记录集79     Set QuerySql = rst    返回记录集80     Exit Function81 Err:82     MsgBox Err.Description, 64, "QuerySql"83 End Function84 85 Public Function GetFieldValue(FieldValue As Variant) As String86     GetFieldValue = http://www.mamicode.com/IIf(Not IsNull(FieldValue), FieldValue, "")87 End Function