使用转储文件以编程方式创建sqlite数据库

本文关键字:方式 创建 sqlite 数据库 编程 转储 文件 | 更新日期: 2023-09-27 18:29:39

我已经从Sqlite数据库创建了一个转储文件,我想在C#应用程序中基于该文件创建另一个Sqlite数据库。

转储文件示例:

drop table if exists [main].[tblAyah];
CREATE TABLE [main].[tblAyah] (
  [IdAyah] INTEGER NOT NULL PRIMARY KEY ON CONFLICT REPLACE AUTOINCREMENT, 
  [AyahNumber] INTEGER, 
  [Page] INTEGER);
insert into [main].[tblAyah] values(1, 1, 1, 'somthing','somthing');
...

所以我的问题是:

有没有一种特殊的方法可以做到这一点,或者我只需要将文件读取为字符串,然后像这样一个接一个地运行每个命令行:

IEnumerable<string> tblCommand;
//Reading the dump file line by one and adding to tblCommand
using (SqlCeConnection con = new SqlCeConnection(
"DataSource='"|DataDirectory|''newDb.db'";Persist Security Info=False;"))
{
    con.Open();
    foreach (string command in tblCommand)
    using (SqlCeCommand com =
    new SqlCeCommand(command, con))
    {
        com.ExecuteNonQuery();
    }
    con.Close();
}

使用转储文件以编程方式创建sqlite数据库

这可以通过创建一个新连接,将SQL转储读取到内存中,然后使用SQLiteCommand ExecuteNonQuery将转储应用于当前连接来完成。

注意:我建议使用SQLiteConnectionStringBuilder创建连接字符串,使用SQLiteConnection进行连接。问题中不清楚您为什么使用SqlCeConnection

开始之前,请从NuGet安装System.Data.SQLite

using System.Data.SQLite;
// ...
var builder = new SQLiteConnectionStringBuilder
    {
        DataSource = @"C:'<Path to your data directory>'<New database file name>.db",
        Version = 3,
        // Any other connection configuration goes here
    };
string connectionString = builder.ToString();
using(SQLiteConnection databaseConnection = new SQLConnection(connectionString)) {
    // Open the connection to the new database
    databaseConnection.Open();
    // Import the SQL file database dump into the in-memory database
    SQLiteCommand command = databaseConnection.CreateCommand();
    string dumpFile = Path.Combine("Path to your sql dump file", "YourDumpFileName.sql");
    string importedSql = File.ReadAllText(dumpFile);
    command.CommandText = importedSql;
    command.ExecuteNonQuery();
}

一次执行可以执行多个命令。它们必须用";"分隔。试试看。如果你有错误,告诉我们。但是它应该是有效的,并且它是创建表或更新数据库结构的一个很好的解决方案,因为如果一条语句出错,它们都不会被执行。