jeudi 22 janvier 2015

C with SQLite: library routine called out of sequence error from sqlite3_prepare_v2 when using JSON

This is how main function looks:



sqlite3 *db;
sqlite3_stmt *stmt;

if(sqlite3_open("dbName", &db))
{
sqlite3_close(db);
printf("Can't open database: %s\n", sqlite3_errmsg(db));
return(1);
}

char *sql = "INSERT INTO tableName VALUES(:val)";

if(sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
{
sqlite3_close(db);
printf("Can't retrieve data: %s\n", sqlite3_errmsg(db));
return(1);
}

// Some irrelevant code
// Function call like
while(/*condition*/)
{
dostuff(blabla, stmt);
}

sqlite3_finalize(stmt);
sqlite3_close(db);
return 0;


This is how I open, prepare my database, do the function call then finalize and close in main function. And I have a function dostuff(int, sqlite3_stmt *) which has to do some operations and insert different values (variable is val here, the function should read every key and value pairs in JSON formatted text and insert the vals into database starting from first column) into all columns; from first column until last column. This is the function:



void dostuff (int s, sqlite3_stmt *stmt)
{
while (loop)
{
if (n <= 0)
{
loop=0;
}
else
{
json_object *jobj = json_object_new_string(buf);
json_object_object_foreach(jobj, key, val)
{
const int index = sqlite3_bind_parameter_index( stmt, ":val");
sqlite3_bind_text(stmt, index, json_object_to_json_string(val), -1, NULL);

while(sqlite3_step(stmt) == SQLITE_ROW)
{
printf("zz");
}
}
sqlite3_reset(stmt);
if (n < 0)
{
loop=0;
}
}
}
}


What I thought here is after opening and preparing the database in the function I read my string to JSON object. Then for every key and val pair in the JSON object find vals and bind vals with sqlite3_bind_text().


After binding I thought running this code while(sqlite3_step(stmt) == SQLITE_ROW) should run the sql query I wrote and insert vals to the database. After the while loop with sqlite3_reset(stmt) I tried to reset my stmt for next bindings.


Aucun commentaire:

Enregistrer un commentaire