【问题标题】:Retrieve SQL table row count with C++ [closed]使用 C++ 检索 SQL 表行数 [关闭]
【发布时间】:2014-03-08 16:07:37
【问题描述】:

我是 Ubuntu 上使用 sqlite3 的 C++ 新手。

我想获取 SQL 表的行数,因此我想在 C++ 中执行此命令“SELECT COUNT(*) FROM Table”,以便我可以在其他方法中使用该行数。

【问题讨论】:

  • 你试过了吗?
  • 是的。我按照下面的答案。
  • 一个答案可能有用一次,一个概念可能永远有用...take a look at this,如果你还没有。

标签: c++ sql sqlite ubuntu-13.04


【解决方案1】:

c/c++ API 使用回调,如the documentation 中所述。您可以使用 *pArg 参数在回调和主代码之间传递值。我稍微修改了他们文档中的代码以获取行数。

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

static int callback(void *count, int argc, char **argv, char **azColName) {
    int *c = count;
    *c = atoi(argv[0]);
    return 0;
}

int main(int argc, char **argv) {
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    int count = 0;

    rc = sqlite3_open("test.db", &db);
    if (rc) {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return(1);
    }
    rc = sqlite3_exec(db, "select count(*) from mytable", callback, &count, &zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    } else {
        printf("count: %d\n", count);
    }
    sqlite3_close(db);
    return 0;
}

【讨论】:

  • 非常感谢!这就是我想要的! :)
  • @VeraAung 很高兴我能帮上忙 :) 如果您对此感到满意,请将此答案标记为正确(绿色复选框轮廓)
猜你喜欢
  • 1970-01-01
  • 2015-11-21
  • 2019-12-18
  • 2015-02-02
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多