SQLite返回NULL行

时间:2015-12-15 17:09:57

标签: c++ sqlite

我无法从数据库中选择和显示表格。我从查询中获取了正确的行数,但所有行都是SQLite NULL值(0或0.0)。如果我在SQLiteStudio中使用相同的查询,一切运行正常。我可能做了一些明显错误的事情,但我不知道是什么。

    sqlite3 *db;
    char *zErrMsg = 0;

    char const* const command = "Select * FROM Location";

    sqlite3_open("DB.db3", &db);

    sqlite3_stmt *stmt = NULL;
    string t;
    int rc = sqlite3_prepare_v2(db, command, -1, &stmt, NULL);
    int row_counter = 0;

    while (1) {
    row_counter++;
        int rc = sqlite3_step(stmt);
        if (rc == SQLITE_DONE)
            break;
        if (rc != SQLITE_ROW) {
            break;
        }
    }

    for (int i = 0; i < row_counter; i += 4)
    {
        t += "LocationID = " + to_string(sqlite3_column_int(stmt, i)) + "\n" +
            "PositionX = " + to_string(sqlite3_column_double(stmt, i + 1)) + "\n" +
            "PositionY = " + to_string(sqlite3_column_double(stmt, i + 2)) + "\n" +
            "PositionZ = " + to_string(sqlite3_column_double(stmt, i + 3)) + "\n";
    }

    WriteToFile(t, "query_result.txt");
    sqlite3_finalize(stmt);

这里是query_result.txt

LocationID = 0
PositionX = 0.000000
PositionY = 0.000000
PositionZ = 0.000000
LocationID = 0
PositionX = 0.000000
PositionY = 0.000000
PositionZ = 0.000000
LocationID = 0
PositionX = 0.000000
PositionY = 0.000000
PositionZ = 0.000000

1 个答案:

答案 0 :(得分:2)

我认为您需要访问SQLITE_ROW的if语句中的列值。在您尝试获取列值时,结果集已经被迭代,并且stmt不再指向有效行。请参阅我在下面所做的更改,以获取我正在谈论的内容的示例。这假定值在0到3列中。

    while (1) {
row_counter++;
    int rc = sqlite3_step(stmt);
    if (rc == SQLITE_DONE)
        break;
    if (rc == SQLITE_ROW) {
          t += "LocationID = " + to_string(sqlite3_column_int(stmt, 0)) + "\n" +
            "PositionX = " + to_string(sqlite3_column_double(stmt, 1)) + "\n" +
            "PositionY = " + to_string(sqlite3_column_double(stmt, 2)) + "\n" +
            "PositionZ = " + to_string(sqlite3_column_double(stmt, 3)) + "\n";
    }
}