Question

I'm trying to update a name column inside sqlite database on my C program using the following function:

void update_name(int row, wchar_t* name, int maxnamelen){
    const wchar_t* update_tempate = L"UPDATE mytable SET name='%s' WHERE(id=%d);";
    wchar_t* update = calloc(sizeof(wchar_t*), maxnamelen+wcslen(update_template));
    swprintf(update, update_template, name, row);
    sqlite3_stmt *stmt;
    sqlite3_prepare16(sqdb, update, sizeof(update), &stmt, 0);
    sqlite3_step(stmt);
    sqlite3_finalize(stmt);
}

but I don't get the row updated unfortunately, because I get the error near "UP" : syntax error.

How can I fix that problem?

Was it helpful?

Solution

The third parameter of sqlite3_prepare16 must be the length of the statement, in bytes.

However, sizeof(update) is the size of the update variable, which is just a pointer, which happens to have the same size as two characters.

You have to give either the actual length (which was already computed by swprintf), or just -1.


Please note that this will still blow up when the name contains a quote. You should use parameters to avoid such formatting problems:

void update_name(int row, wchar_t* name)
{
    const wchar_t* update = L"UPDATE mytable SET name=? WHERE id=?";
    sqlite3_stmt *stmt;
    // error handling is missing
    sqlite3_prepare16(sqdb, update, -1, &stmt, 0);
    sqlite3_bind_text16(stmt, 1, name, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 2, row);
    sqlite3_step(stmt);
    sqlite3_finalize(stmt);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top