I have to check if a table exists before it is created, by reading How do I check in SQLite whether a table exists?, I use sqlite3_exec to do one step query with
SELECT name FROM sqlite_master WHERE type = 'table' AND name ='table1';
and use the callback to set a flag to identify the table exists or not. Unfortunately, the callback will not be called, if the table is not yet created.
Why the callback is not being called? I know that callback is not called for queries without output results, e.g. "create table" etc, and only called with "SELECT" queries. But I am not aware that it may not even be called for "SELECT".
The following is the code sample to reproduce the problem.
#include <stdio.h>
#include <sqlite3.h>
bool isExist=false;
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
printf("I am being called\n");
if (argc>0) isExist = true;
return 0;
}
int main(int argc, char **argv){
sqlite3 *db;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return(1);
}
//char* sqlCreateTable = "CREATE TABLE table1(name TEXT);";
//rc = sqlite3_exec(db, sqlCreateTable, callback, 0, &zErrMsg);
// callback will not be called if table is not yet created
char* sql_hasTable = "SELECT name FROM sqlite_master WHERE type = 'table' AND name ='table1';";
rc = sqlite3_exec(db, sql_hasTable, callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}