c# sqlite导出导入数据表 作为sql文件

csharp 复制代码
// 创建一个 SQLiteConnection 对象
using (var connection = new SQLiteConnection("Data Source=mydatabase.sqlite"))
{
    // 打开数据库连接
    connection.Open();

    // 查询所有表名
    var tableNames = new List<string>();
    var tablesCommand = new SQLiteCommand("SELECT name FROM sqlite_master WHERE type='table'", connection);
    using (var tablesReader = tablesCommand.ExecuteReader())
    {
        while (tablesReader.Read())
        {
            tableNames.Add(tablesReader.GetString(0));
        }
    }

    // 遍历所有表,生成导出 SQL
    var exportSql = new StringWriter();
    foreach (var tableName in tableNames)
    {
        // 查询表结构
        var schemaCommand = new SQLiteCommand($"PRAGMA table_info({tableName})", connection);
        var schemaReader = schemaCommand.ExecuteReader();

        // 生成 CREATE TABLE 语句
        exportSql.WriteLine($"-- Table: {tableName}");
        exportSql.Write("CREATE TABLE ");
        exportSql.Write(tableName);
        exportSql.Write(" (");
        bool firstColumn = true;
        while (schemaReader.Read())
        {
            string columnName = schemaReader.GetString(1);
            string columnType = schemaReader.GetString(2);
            bool notNull = !schemaReader.IsDBNull(3) && schemaReader.GetInt32(3) != 0;
            bool primaryKey = !schemaReader.IsDBNull(5) && schemaReader.GetInt32(5) != 0;

            if (!firstColumn)
            {
                exportSql.Write(",");
            }
            exportSql.Write(columnName);
            exportSql.Write(" ");
            exportSql.Write(columnType);
            if (notNull)
            {
                exportSql.Write(" NOT NULL");
            }
            if (primaryKey)
            {
                exportSql.Write(" PRIMARY KEY");
            }
            firstColumn = false;
        }
        exportSql.Write(");");
        exportSql.WriteLine();

        // 查询表数据
        var dataCommand = new SQLiteCommand($"SELECT * FROM {tableName}", connection);
        using (var dataReader = dataCommand.ExecuteReader())
        {
            // 生成 INSERT 语句
            while (dataReader.Read())
            {
                exportSql.Write($"INSERT INTO {tableName} VALUES (");
                bool firstValue = true;
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    if (!firstValue)
                    {
                        exportSql.Write(",");
                    }
                    object value = dataReader.GetValue(i);
                    if (value == null)
                    {
                        exportSql.Write("NULL");
                    }
                    else if (value is string)
                    {
                        exportSql.Write($"'{value.ToString().Replace("'", "''")}'");
                    }
                    else if (value is DateTime)
                    {
                        exportSql.Write($"'{((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss.fff")}'");
                    }
                    else
                    {
                        exportSql.Write(value.ToString());
                    }
                    firstValue = false;
                }
                exportSql.Write(");");
                exportSql.WriteLine();
            }
        }
        exportSql.WriteLine();
    }

    // 将导出 SQL 写入到文件
    File.WriteAllText("export.sql", exportSql.ToString());
}
csharp 复制代码
public void ImportSqlFile(string sqlFilePath, string databaseFilePath)
{
    // 读取 SQL 文件内容
    string sql = File.ReadAllText(sqlFilePath);

    // 创建一个新的 SQLiteConnection 对象
    using (var connection = new SQLiteConnection($"Data Source={databaseFilePath}"))
    {
        // 打开数据库连接
        connection.Open();

        // 创建一个 SQLiteCommand 对象,并执行 SQL 文件中的 SQL 语句
        using (var command = new SQLiteCommand(sql, connection))
        {
            command.ExecuteNonQuery();
        }
    }

    Console.WriteLine("SQL 文件导入成功!");
}
相关推荐
gc_22996 分钟前
学习C#调用AspNetCoreRateLimit包限制客户端访问次数(4:源码分析)
c#·coreratelimit
Han.miracle9 分钟前
JavaEE--网络编程 http请求 :URL 方法get 和 post
数据库·sql·计算机网络
czhc11400756631 小时前
WinForm 1130 monthCalendar NumbericUpDown Timer
c#·winform
f***28141 小时前
SQL sever数据导入导出实验
数据库·sql·oracle
q***31141 小时前
【MySQL】SQL菜鸟教程(一)
sql·mysql·oracle
sali-tec2 小时前
C# 基于halcon的视觉工作流-章65 点云匹配-基于形状
开发语言·人工智能·算法·计算机视觉·c#
缺点内向2 小时前
如何在C#中为文本内容添加行号?
开发语言·c#·word·.net
e***75392 小时前
MySQL错误-this is incompatible with sql_mode=only_full_group_by完美解决方案
android·sql·mysql
Blossom.1182 小时前
基于知识图谱+LLM的工业设备故障诊断:从SQL日志到可解释推理的实战闭环
人工智能·python·sql·深度学习·算法·transformer·知识图谱
c***42102 小时前
python的sql解析库-sqlparse
数据库·python·sql