Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Programmatically create sqlite db if it doesn't exist?

I am trying to create an sqlite db programmatically if it doesn't exist. I have written the following code but I am getting an exception at the last line.

if (!System.IO.File.Exists("C:\Users\abc\Desktop\1\synccc.sqlite"))
{
    Console.WriteLine("Just entered to create Sync DB");
    SQLiteConnection.CreateFile("C:\Users\abc\Desktop\1\synccc.sqlite");
    string sql = "create table highscores (name varchar(20), score int)";
    SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
    command.ExecuteNonQuery();
}
sqlite2 = new SQLiteConnection("Data Source=C:\Users\abc\Desktop\1\synccc.sqlite");

I get the exception at the line command.ExecuteNonQuery(); The exception is Invalid operation exception was unhandled. Is there any other way to add an sqlite file to your project? Can I do it manually? If not then how can I solve the above issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To execute any kind of data definition command on the database you need an open connection to pass the command. In your code you create the connection AFTER the execution of the query.

Of course, after that creation, you need to open the connection

if (!System.IO.File.Exists(@"C:UsersabcDesktop1synccc.sqlite"))
{
    Console.WriteLine("Just entered to create Sync DB");
    SQLiteConnection.CreateFile(@"C:UsersabcDesktop1synccc.sqlite");
    
    using(var sqlite2 = new SQLiteConnection(@"Data Source=C:UsersabcDesktop1synccc.sqlite"))
    {
        sqlite2.Open();
        string sql = "create table highscores (name varchar(20), score int)";
        SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
        command.ExecuteNonQuery();
    }
}

However, if you use the version 3 of the provider, you don't have to check for the existence of the file. Just opening the connection will create the file if it doesn't exists.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...