用vb写程序的时候,经常需要让DataGrid控件显示数据库的内容,一般都是通过把DataGrid和ADO控件绑定实现的,这样比较麻烦。后来我就想写代码实现这个功能,代码如下:
Public Function GetMDBRecordset(SQL As String, DatabasePath As String, Optional DatabasePassword As String) As Recordset
On Error GoTo ErrorStats
Dim wadoConnection As New Connection
Dim wadoRecordset As New Recordset
Dim PasswordString As String
If Len(DatabasePassword) <> 0 Then
PasswordString = ";Persist Security Info=False;Jet OLEDB:Database Password=" & DatabasePassword
End If
wadoConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabasePath & PasswordString
With wadoRecordset
.ActiveConnection = wadoConnection
.Source = SQL
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
Set GetMDBRecordset = wadoRecordset
Exit Function
ErrorStats:
MsgBox "错误号是:" & Err.Number & vbCrLf & "错误详细信息:" & Err.Description
End Function
在一个Button的Click事件中添加如下代码:
Set datagrid1.DataSource = GetMDBRecordset("select * from table1", "f:\db1.mdb")
这样确实能打开数据库,但是DataGrid里死活不出现内容,经过测试,证明数据库确实被打开了,只是Datagrid控件里没有显示出来。
后来无意中发现同事所写的一个打开数据库的函数,里面给Recordset对象设定了一个CursorLocation=adUseClient,这样,就能在datagrid里显示出来内容了,真是奇怪啊。
代码片断如下:
With wadoRecordset
.ActiveConnection = wadoConnection
.Source = SQL
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.CursorLocation = adUseClient
.Open
End With
呵呵,这样就好了。