VB 读取ACCESS数据库问题?将access某个字段的数据读取到textbox里面,要注释好! 回答好,我追分

2024-12-07 14:49:07
推荐回答(3个)
回答1:

假设数据库名为aa。mdb
Dim adocn As New ADODB.Connection

Private Sub Command1_Click()
If Text1.Text = "" Then

Else
Dim rs As New ADODB.Recordset
Dim strSql As String
strSql = "select * from ID where id=" & Trim(Text1.Text)
adocn.Open
rs.Open strSql, adocn, 3, 3
If rs.EOF And rs.BOF Then
Text2.Text = ""
Text3.Text = ""

Set rs = Nothing
adocn.Close
MsgBox "没有查询到符合您要求的信息!", vbCritical + vbOKOnly, "信息"
Exit Sub
Else
Text2.Text = rs.Fields("uid")
Text3.Text = rs.Fields("password")

Set rs = Nothing
adocn.Close
End If

End If
End Sub

Private Sub Form_Load()
adocn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\aa.mdb;Persist Security Info=False"
End Sub

回答2:

'工程引用ado2.0
Dim adoPrimaryRS As Recordset ‘定义记录集
Dim db As Connection 定义ado连接

Private Sub Command1_Click()
dbpath = "你的数据库文件"
Set db = New Connection
db.Open "PROVIDER=Microsoft.Jet.OLEDB.3.51;Data Source=" & dbpath & ";" ‘打开连接
Set adoPrimaryRS = New Recordset
adoPrimaryRS.Open "select * from id where [id]=" & text1.Text, db, adOpenStatic, adLockOptimistic ’根据text1的内容生成记录集
If adoPrimaryRS.RecordCount > 0 Then ‘如果记录数大于零
text2.Text = adoPrimaryRS.Fields(1).Value ’ text2中显示第二个字段
text3.Text = adoPrimaryRS.Fields(2).Value ’ text3中显示第三个字段
End If
'以下关闭连接与记录集
adoPrimaryRS.Close
db.Close
Set adoPrimaryRS = Nothing
Set db = Nothing

End Sub

回答3:

新建一个工程,在窗体上添加您所需要的控件,
点“工程”菜单——》“引用”,选择Micosoft ActiveX Date objects 2.7 library

在Access中建立数据库

这里我假设你的数据库叫“费率”=,只有这一个表。

填写代码如下:

Option Explicit

Private cnnMain As New ADODB.Connection

Private Sub Combo1_Click()

Dim rs As New ADODB.Recordset

If Combo1.Text <> "" Then

rs.Open "select 出保费 from 费率 where 车型='" & Combo1.Text & "'", cnnMain, adOpenKeyset, adLockReadOnly

If rs.RecordCount > 0 Then

Text1.Text = rs!出保费 & ""

Else
Text1.Text = ""

End If

Else

Text1.Text = ""

End If

Set rs = Nothing

End Sub

Private Sub Form_Load()

With Combo1

.Style = 2

End With

Call OpenConnect

call ListType

End Sub
'列出车型
Private Sub ListType()

Dim i As Long

Dim rs As New ADODB.Recordset

With rs

.Open "select distinct 车型 from 费率", cnnMain, adOpenKeyset, adLockReadOnly

Combo1.Clear

For i = 1 To .RecordCount

Combo1.AddItem rs!车型 & ""

.MoveNext

Next i

End With

Set rs = Nothing
End Sub

Private Sub OpenConnect()

With cnnMain

If .State <> adStateClosed Then .Close

.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & 您的Access数据库文件路径 & ";Persist Security Info=False"

.Open

End With

End Sub

这样够详细了吧?