简体   繁体   English

使用System.Data.SQLite,如何使用相对路径在连接字符串中指定数据库文件

[英]With System.Data.SQLite how do you specify a database file in the connect string using a relative path

Wanting to deploy my project on different servers I would prefer to be able to specify a connect string using a relative path. 想要将项目部署在不同的服务器上,我希望能够使用相对路径指定连接字符串。 I can't seem to get that to work and want to know if there is some trick to it...? 我似乎无法使它正常工作,并且想知道是否有一些窍门...?

A suggestion 一条建议

You could build the absolute path in the app and pass that in the connection string. 您可以在应用程序中构建绝对路径,然后在连接字符串中传递该绝对路径。

So, if you know that the database file is in the database subfolder of the application folder, you could do something like this (C#): 因此,如果您知道数据库文件位于应用程序文件夹的database子文件夹中,则可以执行以下操作(C#):

    string relativePath = @"database\myfile.s3db";
    string currentPath;
    string absolutePath;
    string connectionString;

    currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    absolutePath = System.IO.Path.Combine(currentPath,relativePath);

    connectionString = string.Format("DataSource={0}", absolutePath);

    SQLiteConnection cnn = new SQLiteConnection(connectionString);

(Someone can probably correct me on how to get the current path). (有人可能会在如何获取当前路径方面纠正我)。

How about this? 这个怎么样?

"Data Source=|DataDirectory|mydb.db;..."

I believe |DataDirectory| 我相信|DataDirectory| point to the directory where your app is located. 指向您的应用程序所在的目录。 I use NHibernate and it works with the following: 我使用NHibernate,它可以在以下环境下工作:

<add key="hibernate.connection.connection_string"
       value="Data Source=|DataDirectory|mydb.db;Version=3;Compress=False;synchronous=OFF;" >

Like this: 像这样:

String currentPath = System.IO.Path.GetDirectoryName( Application.ExecutablePath ); 字符串currentPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM