I am writing a C program in Linux that uses a local SQLite database to work with and synchronizes the data to a remote MySQL every X minutes or hours.
The table has a SYN column to mark the rows that have been successfully synchronized (to synchronize them only once and delete them if needed). Right now I just do a select in the SQLite table and, in the callback, a remote insert/update in the MySQL database.
I am trying to figure out how to update the SYN field in the SQLite table if the MySQL insert/update is done ok. For that, it would be fine if I could do an update query to the SQLite table inside the callback because it is there where I check if the MySQL query has success. Is that possible? would it be efficient? I could also store an array of row index to update later but I would have to reallocate the array since I don't know in advance how many rows will need to be updated..
This is what I am doing:
int synchronize_remote_DB(void){
int rc;
char *zErrMsg = NULL;
/************************ OPEN DATABASES *************************/
/*** LOCAL SQLITE ***/
// already opened from the program start-up
/*** REMOTE MySQL ***/
mysql_db_conn = mysql_init(NULL);
if(mysql_db_conn == NULL){
fprintf(stderr, "Error allocating MYSQL structure\n");
return -1;
}
if(!mysql_real_connect(mysql_db_conn, MYSQL_SERVER_IP, MYSQL_DB_USER, MYSQL_DB_PASS, MYSQL_DB_DBNAME, 0, NULL, 0)){
fprintf(stderr, "Failed to connect to remote MySQL database: %s\n", mysql_error(mysql_db_conn));
return -1;
}
/************************ SYNC USER TABLE *************************/
rc = sqlite3_exec(sqlite_db_conn, "select * from USER where SYN=0;", callback_sync_UserTable, NULL, &zErrMsg);
if(rc != SQLITE_OK){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
goto error;
}
And, in the callback:
static int callback_sync_UserTable(void *NotUsed, int argc, char **argv, char **azColName){
char sql_query[512];
memset(sql_query, '\0', sizeof(sql_query));
// BUILD SQL QUERY FOR REMOTE MYSQL DATABASE
snprintf(sql_query, sizeof(sql_query)-1, "INSERT INTO USER(DEVICE_ID,USER_NAME,C1,C2) VALUES("
"%s,\"%s\",%s,%s) ON DUPLICATE KEY UPDATE "
"DEVICE_ID=%s,USER_NAME=\"%s\",C1=%s,C2=%s;",
argv[USRTABLE_DEVICE_ID], argv[USRTABLE_UNAME], argv[USRTABLE_C1], argv[USRTABLE_C2],argv[USRTABLE_DEVICE_ID], argv[USRTABLE_UNAME], argv[USRTABLE_C1], argv[USRTABLE_C2]);
// EXECUTE SQL QUERY IN MYSQL
if(mysql_query(mysql_db_conn, sql_query)){
fprintf(stderr, "MySQL error: %s\n", mysql_error(mysql_db_conn));
}else{
fprintf(stderr, "Remote USER table update OK\n");
// HERE UPDATE LOCAL SQLITE TABLE USER WITH SYN FIELD = 1 TO MARK THAT IT IS SYNCHRONIZED OK
}
return 0;
}
Can I do an UPDATE inside the callback function? Which is the best way to do it?
Thanks!
Aucun commentaire:
Enregistrer un commentaire