ErrorX
ErrorX

Reputation: 123

How can i save a struct in SQLITE C++

I try to save a simpel struct (vector3) in the sqlite3_bind_blob but I have no idea how this works. If I debug this code the console window crashes. How can i fix this problem?

struct vector3
{
    int X;
    int Y;
    int Z;
};

int main ()
{
    sqlite3 *db = NULL;
    sqlite3_stmt *res = NULL;   

    sqlite3_open_v2("SaveGame1.sav", &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);

    string query = "CREATE TABLE IF NOT EXISTS TestPlayer (vector BLOB)";
    sqlite3_prepare_v2 (db, query.c_str(), query.length(), &res, 0);
    sqlite3_step(res);

    // Try to add mij struct
    vector3 MyLocation;
    MyLocation.X = 100;
    MyLocation.Y = 100;
    MyLocation.Z = 100;

    query = "INSERT INTO TestPlayer (location) VALUES (?);";
    sqlite3_prepare_v2 (db, query.c_str(), query.length(), &res, 0);

    sqlite3_bind_blob (res, 1, &MyLocation, sizeof(vector3), SQLITE_TRANSIENT);
    sqlite3_step(res);

    query = "SELECT * FROM TestPlayer;";
    sqlite3_prepare_v2 (db, query.c_str(), query.length(), &res, 0);
    sqlite3_step(res);

    const vector3 *GetLoc = (const vector3 *) sqlite3_column_blob(res, 0);

    cout << GetLoc->X << endl;

    sqlite3_finalize(res);
    sqlite3_close(db);

    return 0;
}

Upvotes: 5

Views: 2054

Answers (1)

Bukes
Bukes

Reputation: 3718

I believe that sqlite3_column_blob() must be used on the results of a query operation. Try issuing a query for the data that you just inserted

Upvotes: 3

Related Questions