如果它不存在,以编程方式创建sqlite db?

时间:2014-06-12 07:38:32

标签: c# .net visual-studio sqlite

我试图以编程方式创建一个sqlite db,如果它不存在的话。我写了下面的代码但是我在最后一行得到了一个例外。

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");

我在第command.ExecuteNonQuery();行获得例外Invalid operation exception was unhandled例外。有没有其他方法可以将sqlite文件添加到您的项目中?我可以手动完成吗?如果没有,那么我该如何解决上述问题?

1 个答案:

答案 0 :(得分:29)

要在数据库上执行任何类型的数据定义命令,您需要一个打开的连接来传递命令。在代码中,您可以在执行查询后创建连接。

当然,在创建之后,您需要打开连接

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");

    using(var sqlite2 = new SQLiteConnection("Data Source=C:\\Users\\abc\\Desktop\\1\\synccc.sqlite"))
    {
        sqlite2.Open();
        string sql = "create table highscores (name varchar(20), score int)";
        SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
        command.ExecuteNonQuery();
    }
}

但是,如果使用提供程序的版本3,则不必检查文件是否存在。如果文件不存在,只需打开连接即可创建文件。

相关问题