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

我试图以编程方式创建一个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();得到了exceptioncommand.ExecuteNonQuery(); 例外是Invalid operation exception was unhandled 。 有没有其他方法可以将sqlite文件添加到您的项目中? 我可以手动完成吗? 如果没有,那么我该如何解决上述问题呢?

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

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

 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(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,则不必检查文件是否存在。 如果文件不存在,只需打开连接即可创建文件。