Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create SQLite database files in .NET core?

Using System.Data.SQLite I would call SqliteConnection.CreateFile.

What is the equivalent in Microsoft.Data.Sqlite?

like image 605
Jonathan Allen Avatar asked Sep 06 '17 21:09

Jonathan Allen


2 Answers

With Microsoft.Data.Sqlite it is typically taken care of automatically.

When you attempt to open a database with the simple kind of connection string exemplified in the following code, the database will be created, if it does not exist:

using (var connection = new SqliteConnection("Data Source=hello.db")) {
    connection.Open();  //  <== The database file is created here.

    // more code here that creates tables etc.

}

More specifically, this just creates an empty file, which will then be filled with tables etc. when you create those things inside.

But it all depends on the connection mode, which can be specified in the connection string with the keyword "Mode". The default value of that keyword (i.e. when that keyword is omitted) is "ReadWriteCreate" which means that the database is opened for reading and writing, and that it is created it if it doesn't exist. Other values of the keyword "Mode" do not have that effect.

See Microsoft.Data.Sqlite - Connection strings for more information.

like image 197
Magnus Avatar answered Sep 19 '22 13:09

Magnus


Found the System.Data.SQLite source code. It is just this:

/// <summary>
/// Creates a database file.  This just creates a zero-byte file which SQLite
/// will turn into a database when the file is opened properly.
/// </summary>
/// <param name="databaseFileName">The file to create</param>
static public void CreateFile(string databaseFileName)
{
    File.WriteAllBytes(databaseFileName, new byte[0]);
}
like image 37
Jonathan Allen Avatar answered Sep 22 '22 13:09

Jonathan Allen