c++ - 如何从 SQLite 数据库中读取数据?

标签 c++ c database sqlite

我决定使用 SQLite,因为它允许将数据库存储到单个文件中。我想我已经设法用 SQLite Database Browser 做一个数据库.

如何在 C/C++ 程序中读取该数据?

最佳答案

使用 sqlite 读取的示例:

#include <stdio.h>
#include <sqlite3.h>
#include <string.h>


int main(int argc, char** argv)
{
    const char*          username = "satyam";
    char                 q[999];
    sqlite3*             db;
    sqlite3_stmt*        stmt;
    int                  row = 0;
    int                  bytes;
    const unsigned char* text;

    if (2 == argc) {
        username = argv[1];
    }

    q[sizeof q - 1] = '\0';
    snprintf(
        q,
        sizeof q - 1,
        "SELECT ipaddr FROM items WHERE username = '%s'",
        username
    );

    if (sqlite3_open ("test.db", &db) != SQLITE_OK) {
        fprintf(stderr, "Error opening database.\n");
        return 2;
    }

    printf("Query: %s\n", q);

    sqlite3_prepare(db, q, sizeof q, &stmt, NULL);

    bool done = false;
    while (!done) {
        printf("In select while\n");
        switch (sqlite3_step (stmt)) {
        case SQLITE_ROW:
            bytes = sqlite3_column_bytes(stmt, 0);
            text  = sqlite3_column_text(stmt, 1);
            printf ("count %d: %s (%d bytes)\n", row, text, bytes);
            row++;
            break;

        case SQLITE_DONE:
            done = true;
            break;

        default:
            fprintf(stderr, "Failed.\n");
            return 1;
        }
    }

    sqlite3_finalize(stmt);

    return 0;
}

关于c++ - 如何从 SQLite 数据库中读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3957343/

相关文章:

c++ - 为什么 "Attach to Process"不允许其他传输类型? VS 2008

c++ - 在没有对象的情况下推回 vector 中的对象

c++ - protocol buffer GetRepeatedField(反射)代码优化

c - 为什么 strace 遵循不同的执行流程?

c - 不使用字符串库测试字符串相等性

database - MapDB 与常规数据库

c++ - Qt5 中 http 客户端的 Post 方法

c - 正则表达式库错误

sql - 不是 GROUP BY 表达式

mysql - 查找 Actor 在同一部电影中具有多个不同角色的 Actor /电影行