How do I retain database connectivity, with my project, when the source file path changes?

人盡茶涼 提交于 2020-01-21 06:12:26

问题


I am using a Microsoft Access Database in my project; saved to the bin folder. What can I do, to ensure connectivity to that database, when the file path changes?

Imports System.Data.OleDb Public Class Form3

Dim con As New OleDb.OleDbConnection

Dim da As OleDbDataAdapter

Dim ds As New DataSet

Dim str1 As String

    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AARVIII\Documents\DATABASE\MP1.accdb"

回答1:


Your connection string locates your database in a fixed position valid only on your PC.
A simple workaround is to use the |DataDirectory| substitution string.

con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + 
                       "Data Source=|DataDirectory|\MP1.accdb"

in this way, you can control the location of your database through code.
Usually (for a desktop application) the |DataDirectory| substitution string points the same folder where you have installed your application, but you need to have permission to write there and any kind of active database requires write permissions on its files. So this is not the best location for database files.

However you could change the location pointed by DataDirectory using code like this. (Of course put it BEFORE any attempt to talk to the database)

 ' Prepare a string pointing to a subfolder of the common application data 
 Dim appFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
 Dim dbFolder = Path.Combine(appFolder, "MyAppFolder")

 ' Create the folder if it doesn't exist.
 Directory.CreateDirectory(dbFolder)

 ' Change the substitution string kept by DataDirectory
 AppDomain.CurrentDomain.SetData("DataDirectory", dbFolder)

Now the target directory for your database will be C:\programdata\myappfolder where your application has read/write permissions

More info on DataDirectory

Where is DataDirectory
DataDirectory where is documented




回答2:


Yea, you should use:

con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "MP1.accdb"

And have the database file in the same folder as you startup .exe...




回答3:


I use this simple code and I can move the folder any where

conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\myDatabase.mdb"

Make sure to save the access file in the bin folder for this connection string to work.



来源:https://stackoverflow.com/questions/17996907/how-do-i-retain-database-connectivity-with-my-project-when-the-source-file-pat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!