My database is located outside the application folder Example:
Database: SampleApplication\\Database\\Database.sqlite
Application: SampleApplication\\Application\\program.cs
My code is as below.
string relativePath = @"SampleApplication\Database\Database.sqlite";
string currentPath;
string absolutePath;
string connectionString;
currentPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
absolutePath = Path.Combine(currentPath, relativePath);
connectionString = string.Format("Data Source={0};Version=3;Pooling=True;Max Pool Size=100;", absolutePath);
m_dbConnection = new SQLiteConnection(connectionString);
m_dbConnection.Open();
Alright, I figured it out guys.
string relativePath = @"Database\Database.sqlite";
var parentdir = Path.GetDirectoryName(Application.StartupPath);
string myString = parentdir.Remove(parentdir.Length -34, 34);
string absolutePath = Path.Combine(myString, relativePath);
string connectionString = string.Format("Data Source={0};Version=3;Pooling=True;Max Pool Size=100;", absolutePath);
m_dbConnection = new SQLiteConnection(connectionString);
m_dbConnection.Open();
I removed the characters from the parentdir
till SampleApplication\\
and added it with the relativePath
. That makes an absolutePath
to the database
. The number 34
in the third line signifies how many characters to be remove from the end of parentdir
.
尝试这个
var parentdir =Path.GetDirectoryName(System.Windows.Forms.Application.StartupPath);
I guess you need to modify your connection string, so for basic connect to SQL LITE DATABASE, you would do this:
Data Source=c:\mydb.db;Version=3;
enter code here
In memory database:
Data Source=:memory:;Version=3;New=True;
With password
Data Source=c:\mydb.db;Version=3;Password=myPassword;
You could do this also in your c# code:
var connectionString = @"data source=c:\TestData\testsqldata.s3db; Version=3;"
connection = new SQLiteConnection(connectionString);
connection.Open();
In an ASP CORE project if your db is in Data folder, write the following code in startup.cs :
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyContext>(options =>
options.UseSqlite("Data Source=" +
Path.Combine(Directory.GetCurrentDirectory(), "Data\\sqlite.db"))
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.