19

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

What is the equivalent in Microsoft.Data.Sqlite?

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

Comments

14

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]);
}

1 Comment

shorter version, File.WriteAllBytes(databaseFileName, new byte[0]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.