首先要在工程的引用中选上Microsoft ActiveX Data Objects 2.5 Library
然后在事件中就可以定义相关的变量进行连接了
下面的例子可能对您有用:
Private Sub Command1_Click()
Dim Conn As New ADODB.Connection
Dim Rs As New ADODB.Recordset
Conn.Open connstring ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & “数据库的路径和名字” & ";Persist Security Info=True;Jet OLEDB:Database Password= & "数据库密码"
sql = "Select * From “ & ”表名" & where ID=20"
Rs.Open sql, Conn, 1, 3
If NOT rs.eof then
m_date= rs("日期型字段的名字")
m_data= rs("数值型字段的名字")
end if
上面的例子实现了查询
如果是要添加,删除,更新等操作,只要编写相应的SQL语句,再用
Conn.Execute SQL 就可以了,如:
添加的:
SQL="Insert Into [UserInfo](User,Password) Values('aaaa','1234')"
Conn.Execute SQL '执行后,就添加了一条记录
删除:
SQL="Delete From [UserInfo] Where User='aaaa'"
Conn.Execute SQL '删除用户名为aaaa的用户记录
更新:
SQL="Update [UserInfo] Set Password='abcdefg' Where User='aaaa'"
Conn.Execute SQL '执行后,修改用户aaaa的密码为abcdefg
以上只是示例,在实际使用过程中,可以将一些内容用控件输入等方式进行,这样就有很大的灵活性了
追问:
Conn.Open connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\newdata.mdb;Persist Security Info=True;Jet OLEDB:Database Password=123"
这一句发生错误
追答:
您把:
Conn.Open connstring ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & “数据库的路径和名字” & ";Persist Security Info=True;Jet OLEDB:Database Password= & "数据库密码"
这句改为下面的两句 您再试试
connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & "数据库的路径和名字" & ";Jet OLEDB:Database password=" & "数据库密码"
Conn.Open connstring
假设我的数据库里有十条数据,我要将它们全部都循环读取出来,存到一个数组变量中,该怎么做呢?每个字段存一个数组
这要看您数据库里保存的数据的类型了。
如果都可以转换成字符串型的话
定义一个二维数组就可以了
例如:
1
2
3
4
5
6
7
8
9
10
dim m_data() as string
dim i as integer
do until rs.eof
ReDim Preserve m_data(Rs.Fields.Count - 1, i)
For j = 0 To Rs.Fields.Count - 1
m_data(j, i) = IIf(IsNull(Rs.Fields(j)), "", Rs.Fields(j))
next j
rs.MoveNext
i=i+1
loop
Private Sub Form_Load()
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim i As Integer
Dim sFieldName As String
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Layer.mdb;Persist Security Info=False" '如需连接网络的,将Data Sourc写出完整路径即可
rs.Open "switchtime", con, adOpenStatic, adLockOptimistic, adCmdTable
For i = 0 To rs.Fields.Count - 1
sfilename = sfilename & rs.Fields(i).Name & vbTab
Next
MsgBox sFieldName
rs.Close
Set rs = Nothing
con.Close
Set con = Nothing
End Sub