VB通过ADODB与ACCESS数据交换实例
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
VB与ACCESS数据交换实例
准备步骤:
1)建立一个简单的ACESS数据库,命名为student,创建一个表:Chinese,字段:ID,姓名,成绩
2)打开VB6.0,创建一个窗口,添加引用:
添加部件:MSHFlexGrid
设计窗口如下图所示:
3编写代码:
Option Explicit
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim a As String
'子程序
Private Sub reshow()
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & App.Path & "\student.mdb;" & "Persist Security Info=False"
conn.Open
rs.Open "select * from Chinese", conn, adOpenKeyset, adLockReadOnly
Set MSHFlexGrid1.DataSource = rs
MSHFlexGrid1.Sort = 3
rs.Close
conn.Close
End Sub
'删除记录
Private Sub Command1_Click()
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & App.Path & "\student.mdb;" & "Persist Security Info=False"
conn.Open
rs.Open "select * from Chinese where ID=" & Val(Text4.Text), conn, adOpenKeyset, adLockOptimistic
'上句表示查询语句ID=Val(Text4.Text)
rs.Delete
rs.Update
reshow
Text4.Text = ""
rs.Close
conn.Close
End Sub
'修改记录
Private Sub Command2_Click()
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & App.Path & "\student.mdb;" & "Persist Security Info=False"
conn.Open
rs.Open "select * from Chinese where ID=" & Val(Text1.Text), conn, adOpenKeyset, adLockOptimistic
rs.Fields(0).Value = Val(Text1.Text)
rs.Fields(1).Value = Text2.Text
rs.Fields(2).Value = Text3.Text
rs.Update
MsgBox "记录修改成功!"
reshow
End Sub
'刷新纪录
Private Sub Command3_Click()
reshow
End Sub
'连接ACCESS
Private Sub Form_Load()
reshow
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
End Sub
'添加纪录
Private Sub ADD_Click()
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & App.Path & "\student.mdb;" & "Persist Security Info=False"
conn.Open
rs.Open "select * from Chinese", conn, adOpenKeyset, adLockOptimistic rs.AddNew '添加记录
Text1.SetFocus
If Text1.Text = "" Then
MsgBox "不能为空!"
Text1.SetFocus
Exit Sub
Else
rs.Fields(0).Value = Val(Text1.Text)
rs.Fields(1).Value = Text2.Text
rs.Fields(2).Value = Text3.Text
rs.Update
End If
rs.Close
conn.Close
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
reshow
End Sub