You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++操作SQLite无回调查询仅返回前100行,剩余数据无法输出

问题原因

你的代码只打印前100行,核心问题是循环条件错误:for (int i = 0; i < SQLITE_ROW; i++)。SQLITE_ROW是SQLite定义的宏,值为100,这个宏的作用是sqlite3_step()返回它表示当前有数据行可以读取,而非用来作为循环次数的上限。所以你的循环只执行了100次,自然只打印100行。

修正后的代码

正确的做法是用while循环持续调用sqlite3_step(),直到它返回非SQLITE_ROW的状态(比如SQLITE_DONE,表示所有行读取完毕)。同时保留原来的条目计数逻辑控制每行显示两个数据:

#include <iostream>
#include <sqlite3.h>

sqlite3 *db;
int rc;
sqlite3_stmt *stmt;

int main()
{
    rc = sqlite3_open("PairToSqliteDB.db", &db);
    if (rc)
    {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        return 0;
    }
    else
    {
        fprintf(stderr, "Opened database successfully\n");
    }

    // 预处理SQL语句,检查返回值避免潜在错误
    rc = sqlite3_prepare_v2(db, "select Item_id, ItemName, SellPrice from SARISARI", -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Failed to prepare statement: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;
    }

    int c = 2;
    int i = 0;
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW)
    {
        if (i % c == 1)
            printf(" | ");
        printf("%3i: %-12s = P%6.2f", sqlite3_column_int(stmt, 0), 
               reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1)), 
               sqlite3_column_double(stmt, 2));
        if (i % c == 1)
            printf("\n");
        i++;
    }

    // 检查循环退出的原因是否是正常结束
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Error while reading rows: %s\n", sqlite3_errmsg(db));
    }

    sqlite3_finalize(stmt); // 必须释放预处理语句
    sqlite3_close(db);
    return 0;
}
关键修改点
  • 把for循环改成while循环,以sqlite3_step()的返回值作为循环条件,确保读取所有数据行
  • 增加了sqlite3_prepare_v2()的返回值检查,避免预处理失败后继续执行导致的错误
  • 添加了sqlite3_finalize(stmt),这是必须的操作,用来释放预处理语句占用的资源
  • 把sqlite3_column_text()的返回值做了reinterpret_cast<const char*>,符合C++的类型安全要求
  • 增加了循环退出后的错误检查,方便排查读取过程中可能出现的问题

内容的提问来源于stack exchange,提问作者bong hussain lopez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:25:19