当源文件路径更改时,如何保持与我的项目的数据库连接? [英] How do I retain database connectivity, with my project, when the source file path changes?

查看:25
本文介绍了当源文件路径更改时,如何保持与我的项目的数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用了 Microsoft Access 数据库;保存到 bin 文件夹.当文件路径更改时,我该怎么做才能确保与该数据库的连接?

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?

导入 System.Data.OleDb公开课表格3

Imports System.Data.OleDb Public Class Form3

Dim con 作为新的 OleDb.OleDbConnection

Dim con As New OleDb.OleDbConnection

Dim da As OleDbDataAdapter

Dim da As OleDbDataAdapter

将 ds 变暗为新数据集

Dim ds As New DataSet

将 str1 淡化为字符串

Dim str1 As String

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

推荐答案

您的连接字符串将您的数据库定位在仅在您的 PC 上有效的固定位置.
一个简单的解决方法是使用 |DataDirectory| 替换字符串.

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"

这样,你就可以通过代码来控制你的数据库的位置了.
通常(对于桌面应用程序)|DataDirectory| 替换字符串指向您安装应用程序的同一个文件夹,但您需要有在那里写入的权限,并且任何类型的活动数据库都需要写入权限它的文件.所以这不是数据库文件的最佳位置.

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.

但是,您可以使用这样的代码更改 DataDirectory 指向的位置.(当然,在任何试图与数据库对话之前把它放在一起)

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)

现在您的数据库的目标目录将是 C:\programdata\myappfolder,您的应用程序具有读/写权限

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

关于数据目录的更多信息

More info on DataDirectory

数据目录在哪里
DataDirectory 在哪里记录

这篇关于当源文件路径更改时,如何保持与我的项目的数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆