'整个程序功能是选择不同的连接方式来进行显示工作,三种方式显示效果完全相同 '下面是主程序过程 Private Sub Command1_Click() Dim selitem As Integer '判断连接数据库的方式 If Option1.Value = True Then selitem = 1 Else If Option2.Value = True Then selitem = 2 Else selitem = 3 End If End If
'选取不同的数据库连接方式 Select Case selitem Case 1: '使用DAO的数据库连接方式 Call ShowByDAO Case 2: '使用ADO的数据库连接方式 Call ShowByADO Case 3: '使用ODBC的数据库连接方式 Call ShowByODBC Case 4: '使用OLEDB的数据库连接方式 Call ShowByOLEDB End Select End Sub
Private Sub ShowByDAO() '使用DAO的数据库连接方式 Dim db As Database Dim rs As Recordset Dim sqlstr$ '存放查询语句 Set db = OpenDatabase(App.Path & "\db1.mdb") sqlstr = "select * from 成绩表" Set rs = db.OpenRecordset(sqlstr) '显示结果 Call GridShow(rs) End Sub
Sub ShowByADO() Dim conn As New ADODB.Connection Dim rs As New ADODB.Recordset '使用数据源来连接数据库 conn.Open "dsn=data" rs.CursorType = adOpenKeyset rs.LockType = adLockOptimistic rs.Open "select * from 成绩表", conn Call GridShowOfADO(rs) End Sub
Sub ShowByODBC() Dim conn As New ADODB.Connection Dim rs As New ADODB.Recordset '使用数据源来连接数据库 conn.Open "Provider=MSDASQL.1;Persist Security Info=False;Data Source=data" rs.Open "select * from 成绩表", conn '显示结果 Call GridShowOfADO(rs) End Sub
Sub ShowByOLEDB() Dim conn As New ADODB.Connection Dim rs As New ADODB.Recordset '使用数据源来连接数据库 conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + App.Path & "\db1.mdb" + ";Persist Security Info=False" rs.Open "select * from 成绩表", conn
'显示结果 Call GridShowOfADO(rs) End Sub
Sub GridShow(rs As Recordset) '对dao方式进行显示工作 MSFlexGrid1.TextMatrix(0, 0) = "姓名" MSFlexGrid1.TextMatrix(0, 1) = "性别" MSFlexGrid1.TextMatrix(0, 2) = "语文" MSFlexGrid1.TextMatrix(0, 3) = "数学" MSFlexGrid1.TextMatrix(0, 4) = "英语" rs.MoveLast MSFlexGrid1.Rows = rs.RecordCount + 1 MSFlexGrid1.Cols = rs.Fields.Count Dim i% i = 1 rs.MoveFirst While (Not rs.EOF)
MSFlexGrid1.TextMatrix(i, 0) = rs.Fields(0) MSFlexGrid1.TextMatrix(i, 1) = rs.Fields(1) MSFlexGrid1.TextMatrix(i, 2) = rs.Fields(2) MSFlexGrid1.TextMatrix(i, 3) = rs.Fields(3) MSFlexGrid1.TextMatrix(i, 4) = rs.Fields(4) rs.MoveNext i = i + 1 'If (rs.EOF = True) Then ' Exit For Wend End Sub
Sub GridShowOfADO(rs As ADODB.Recordset) '对ado方式进行显示工作 MSFlexGrid1.TextMatrix(0, 0) = "姓名" MSFlexGrid1.TextMatrix(0, 1) = "性别" MSFlexGrid1.TextMatrix(0, 2) = "语文" MSFlexGrid1.TextMatrix(0, 3) = "数学" MSFlexGrid1.TextMatrix(0, 4) = "英语" '注意recordcount属性必须在当前记录指针在最后一条记录时才会返回正确的值 rs.MoveLast MSFlexGrid1.Rows = rs.RecordCount + 1 MSFlexGrid1.Cols = rs.Fields.Count Dim i% i = 1 rs.MoveFirst While (Not rs.EOF) MSFlexGrid1.TextMatrix(i, 0) = rs.Fields(0) MSFlexGrid1.TextMatrix(i, 1) = rs.Fields(1) MSFlexGrid1.TextMatrix(i, 2) = rs.Fields(2) MSFlexGrid1.TextMatrix(i, 3) = rs.Fields(3) MSFlexGrid1.TextMatrix(i, 4) = rs.Fields(4) rs.MoveNext i = i + 1 Wend End Sub
Private Sub Command2_Click() End End Sub |