1

I'm having trouble selecting and displaying a table from my database. I'm getting the correct number of rows from my query but all of them are SQLite NULL values (0 or 0.0). Everything runs fine if I use the same query in SQLiteStudio. I'm probably doing something obviously wrong but I don't know what.

    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);

Here's the 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 Answer 1

2

I think you need to access the column values inside of the if statement for SQLITE_ROW. At the point you're trying to get the column values, the result set has already been iterated and stmt no longer points to a valid row. See the changes I made below for an example of what I'm talking about. This assumes the values are in columns 0 to 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";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.