VB数据库如何用text文本框插入数据和读取显示数据

2024-10-28 18:15:07
推荐回答(2个)
回答(1):

一 查阅
在Text1的KeyPress事件中加入代码,查阅时,在Text1里输入数据后,按Enter键作结束
Private Sub Text1_KeyPress(KeyAscii AsInteger)
If KeyAscii = 13 Then
Dim X As Integer
Dim CNN As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim SQ2 As String
CNN.Open "Provider=microsoft.jet.oledb.4.0;data source="& App.Path & "\数据库名.mdb"
SQ2 = "select * from 表名"
rst.Open SQ2, CNN, adOpenKeyset, adLockOptimistic
if not rst.EOF then
rst.Movefirst
end if
For X = 1 To rst.RecordCount
If Val(Me.Text1) = rst("A") Then ‘如果字段A是文本格式,Val()函数改为Trim()
Me.Text1 = rst("A")
Me.Text2 = rst("B")
Me.text3 = rst("C")
Me.text4 = rst("D")
Exit For
EndIf
rst.MoveNext
Next X
rst.Close
Set CCN = Nothing
End If
End Sub

二保存
Private Sub 保存_Click()
Dim X As Integer
Dim CNN As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim SQ2 As String
CNN.Open"Provider=microsoft.jet.oledb.4.0;data source=" & App.Path &"\数据库名.mdb"
SQ2 = "select * from 表名"
rst.Open SQ2, CNN, adOpenKeyset,adLockOptimistic
rst.AddNew
rst("A")= Me.Text1
rst("B")= Me.Text2 =
rst("C")=Me.Text3
rst("D")= Me.Text4
rst.update
rst.Close
Set CCN = Nothing
End Sub

三修改 删除
在DataGrid的RowColChange事件里加入
Private Sub DataGrid_RowColChange(LastRow As Variant, ByVal LastCol As Integer)
me.text1=Datagrid.columns(0) '如果字段A是第一列,
end sub

点击修改或 删除 前,需在DataGrid表里点选需要修改或删除的记录,让该记录的第一列出现在textbox1里

Private Sub 修改_Click()

Dim X As Integer
Dim CNN As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim SQ2 As String
CNN.Open"Provider=microsoft.jet.oledb.4.0;data source=" & App.Path &"\数据库名.mdb"
SQ2 = "select * from 表名"
rst.Open SQ2, CNN, adOpenKeyset,adLockOptimistic
if not rst.EOF then
rst.Movefirst
end if
For X = 1 To rst.RecordCount
If Val(Me.Text1) = rst("A") Then '如果字段A是文本格式,Val()函数改为Trim()
rst("A")= Me.Text1
rst("B")= Me.Text2 =
rst("C")=Me.Text3
rst("D")= Me.Text4
rst.update
ExitFor
EndIf
rst.MoveNext
Next X
rst.Close
Set CCN = Nothing
End Sub

Private Sub 删除_Click()
Dim X As Integer
Dim CNN As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim SQ2 As String
CNN.Open"Provider=microsoft.jet.oledb.4.0;data source=" & App.Path &"\数据库名.mdb"
SQ2 = "select * from 表名"
rst.Open SQ2, CNN, adOpenKeyset,adLockOptimistic
if not rst.EOF then
rst.Movefirst
end if
For X = 1 To rst.RecordCount
If Val(Me.Text1) = rst("A") Then '如果字段A是文本格式,Val()函数改为Trim()
rst.delete
Exit For
EndIf
rst.MoveNext
Next X
rst.Close
Set CCN = Nothing
End Sub

回答(2):

文本框本来就具有这个功能,称为数据绑定控件:

在设计时,在它的属性窗口设置它的绑定对象就可以了:
DataSource 属性 选ADODC1
DataField 属性 选对应的字段名

然后加一个按钮:

按钮代码如下:
如果字段A是数值类型
Private Sub Command1_Click()
Adodc1.RecordSource = "Select * from 数据表名 where A=" & Text1.Text
Adodc1.Refresh
End Sub

如果字段A是文本类型
Private Sub Command1_Click()
Adodc1.RecordSource = "Select * from 数据表名 where A='" & Text1.Text & "'"
Adodc1.Refresh
End Sub