Dim sql As String = "select * from login"
Dim Oda As New OleDbDataAdapter(sql, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb")
Dim ds As New DataSet
Oda .Fill(ds, "login")
DataGrid1.DataSource = ds.Tables(0).DefaultView()
'绑定到dataGrid
Dim Oda As New OleDbDataAdapter(sql, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb")
Dim ds As New DataSet
Oda .Fill(ds, "login")
DataGrid1.DataSource = ds.Tables(0).DefaultView()
'绑定到dataGrid
以上体现了OleDbDataAdapter与dataset的优越性,到这时您已经可以从dataset随心所欲到取数据了,而在vb6.0中半面向对象设计的概念使结构体和独立的函数大量的被使用,当然我在这里要用的方法也就是用VB6函数模拟对象了如下步骤:
①:在应用中添加一个对adodb 2.7版本的引用
②添加module模块,在模块中加入以下代码
Public Function newado(SQL As String, AccessDb As String) As ADODB.Recordset
Dim rs As ADODB.Recordset
strconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & AccessDb & ";Persist Security Info=False"
Set rs = New ADODB.Recordset
rs.Open SQL, strconn, adOpenStatic, adLockOptimistic, adCmdText
Set newado = rs
Set rs = Nothing
'rs.CursorLocation = adUseClient
' rs.Open SQL, strconn, adOpenDynamic, adLockBatchOptimistic,adLockBatchOptimistic
End Function
③:这时您已经可以在任意地方方便的申请,使用,回收ADODB.Recordset对象如:Dim rs As ADODB.Recordset
strconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & AccessDb & ";Persist Security Info=False"
Set rs = New ADODB.Recordset
rs.Open SQL, strconn, adOpenStatic, adLockOptimistic, adCmdText
Set newado = rs
Set rs = Nothing
'rs.CursorLocation = adUseClient
' rs.Open SQL, strconn, adOpenDynamic, adLockBatchOptimistic,adLockBatchOptimistic
End Function
dim myado as ADODB.Recordset
set myado =newado("select * from stu","db1.mdb")
while not myado.EOF
'……
myado.next
wend
myado.close
set myado =newado("select * from stu","db1.mdb")
while not myado.EOF
'……
myado.next
wend
myado.close
当然以上函数可以更灵活,就是把Provider也作为参数,但是一般我们是很少改变数据库提供程序的
如果您像与控件绑定,那么需要在公共函数里使用客户端游标语句
rs.CursorLocation = adUseClient
那么这时在为关闭myado时都可以绑定到控件,如:
set dataGrid.datasource=myado
到这里,大家现在也可以像ado.net那样享受到编写代码的方便,无论你写什么数据库项目,都可以马上都把函数复制到新项目的module写立即使用了。