如何优化代码(ADOB连接在Datagrid里显示)
刚学习数据库的连接与记录的显示,能实现最最基本的增加与显示,但觉的代码很重复,哪位能帮忙优化一下不?(不用ADOC控件)
all.zip
(15.69 KB)
'声明变量
Dim cn As New ADODB.Connection
Dim rs1 As ADODB.Recordset
Dim sql$
'启动时就显示表格内容
Private Sub Form_Load()
If cn.State <> adStateClosed Then cn.Close
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\用户目录\我的文档\database1.mdb"
Set rs1 = New ADODB.Recordset
rs1.CursorLocation = adUseClient
rs1.Open "select * from use", cn, adOpenKeyset, adLockOptimistic
Set DataGrid1.DataSource = rs1
End Sub
Private Sub Command1_Click()
'增加新记录
sql = "insert into [use]([字段1],[字段2],[字段3]) values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "') "
Set rs1 = New ADODB.Recordset
rs1.CursorLocation = adUseClient
rs1.Open sql, cn, adOpenKeyset, adLockOptimistic
'更新并显示记录
rs1.Open "select * from use", cn, adOpenKeyset, adLockOptimistic
Set DataGrid1.DataSource = rs1
'准备下次输入
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
End Sub
[此贴子已经被作者于2020-2-15 20:57编辑过]