设置对VB数据库连接的动态路径
笔者的解决方法是利用app.path 来解决这个问题。
一、用data控件进行数据库链接,可以这样:
在form_load()过程中放入:
private form_load()
Dim str As String '定义
str = App.Path
If Right(str, 1) <> "" Then
str = str + ""
End If
data1.databasename=str & "数据库名"
data1.recordsource="数据表名"
data1.refresh
sub end
这几句话的意为,打开当前程序运行的目录下的数据库。
你只要保证你的数据库在你程序所在的目录之下就行了。
二、利用adodc(ADO Data Control)进行数据库链接:
private form_load ()
Dim str As String '定义
str = App.Path
If Right(str, 1) <> "" Then
str = str + ""
End If
str = "Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data Source=" & str & " sl.mdb"
Adodc1.ConnectionString = str
Adodc1.CommandType = adCmdText
Adodc1.RecordSource = "select * from table3"
Adodc1.Refresh
end sub
三、利用DataEnvironment进行数据库链接
可在过程中放入:
On Error Resume Next
If DataEnvironment1.rsCommand1.State <> adStateClosed Then
DataEnvironment1.rsCommand1.Close '如果打开,则关闭
End If
'i = InputBox("请输入友人编号:", "输入")
'If i = "" Then Exit Sub
DataEnvironment1.Connection1.Open App.Path & "userdatabase sl.mdb"
DataEnvironment1.rsCommand1.Open "select * from table3 where 编号='" & i & "'"
'Set DataReport2.DataSource = DataEnvironment1
'DataReport2.DataMember = "command1"
'DataReport2.show
end sub
四、利用ADO(ActiveX Data Objects)进行编程:
建立连接:
dim conn as new adodb.connection
dim rs as new adodb.recordset
dim str
str = App.Path
If Right(str, 1) <> "" Then
str = str + ""
End If
str = "Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data Source=" & str & " sl.mdb"
conn.open str
rs.cursorlocation=aduseclient
rs.open "数据表名",conn,adopenkeyset.adlockpessimistic
用完之后关闭数据库:
conn.close
set conn=nothing