问题 是否有可能以编程方式将SQLite数据库转换为C / C ++中的SQL语句?


我知道的存在 。倾倒 函数在SQLite命令行工具中,而Python有一个 iterdump 模拟.dump函数的命令。

是否有标准的API调用或C / C ++包装器以编程方式提供.dump功能?


6396
2017-08-07 05:53


起源

D'哦!看到 这个问题。 - David Schwartz


答案:


Api似乎没有任何转储功能(http://www.sqlite.org/capi3ref.html),但您可以通过以下方式构建转储:

  • 创建一个将使用缓冲区结果的新函数 sqlite3_exec() 要么 sqlite3_get_table() 并将其转储到文件*

  • 使用Sqlite源代码中提供的转储功能,你可以在(shell.c)。

编辑:添加此示例

/* TODO : This is just a sample code, modify it to meet your need */
void select_and_dump_sqlite3_table(sqlite3 *dbh)
{
    FILE    *dump_file;
    int i;
    sqlite3_stmt *stmt;

    dump_file = fopen(path_to_dump_file, "w");
    if (dump_file == NULL) {
        /* Error handling with errno and exit */
    }

    sqlite3_prepare_v2(dbh, "SELECT name, address, phone FROM Person",
                       0, &stmt, NULL);
    /* dump columns names into the file */
    for (i = 0; i < 3; i++) {
        fprintf (dump_file, "%30s | ", sqlite3_column_name(stmt, i));
    }
    printf ("\n");

    /* Dump columns data into the file */
    while (SQLITE_ROW == sqlite3_step(stmt)) {
        for (i = 0; i < 3; i++) {
          fprintf (dump_file, "%30s | ", sqlite3_column_text (stmt, i));
        }
      printf ("\n");
    }
    /* We're ready to leave */
    sqlite3_finalize (stmt);
}

8
2017-08-07 06:10



你让我自己踢 - “我如何模仿这个C工具的行为,我有C或C ++的源代码?”咄。 :) - dlanod
@dlanod:我在答案中添加了示例代码 - TOC


你可以做一个 SELECT * FROM sqlite_master 获取所有表和索引(每行有一个 type 列将是 'table' 用于桌子和 'index' 对于指数,和 sql 包含用于创建该表/索引的sql语句的列。

然后找到每个表 sqlite_masterSELECT * 从他们(每个 sqlite_master 排有一个 name 列)并写出表中的所有数据。

请参阅SQLite 常问问题 和 命令行shell 页面了解更多信息。


3
2017-08-07 06:09





我不知道是否有预制工具,但你可以自己实现。

首先,通过读取主表来获取模式。之后,您将拥有数据库模式(表名和列)。您将能够自动读取所有数据并为其构建SQL。这不应该太难实现。


0
2017-08-07 06:11