Create SQLite DB with multiple tables in iOS -
in development of ipad applicacion, need database 5 tables, but, don't know why in code, execute 1 statement , don't return error:
const char *sqlstatement = "create table if not exists categorias (id integer primary key, nombre text)"; char *error; if(sqlite3_exec(dienedb, sqlstatement, null, null, &error) == sqlite_ok){ **sqlstatement = "create table if not exist subcategorias (id integer primary key, id_categoria integer, nombre text)";** if(sqlite3_exec(dienedb, sqlstatement, null, null, &error) == sqlite_ok){ sqlstatement = "create table if not exist formatos (id integer primary key, nombre text)"; if(sqlite3_exec(dienedb, sqlstatement, null, null, &error) == sqlite_ok){ sqlstatement = "create table if not exist bebidas (id integer primary key, id_categoria integer, id_subcategoria integer, nombre text, descripcion text, ruta_imagen text)"; if(sqlite3_exec(dienedb, sqlstatement, null, null, &error) == sqlite_ok){ sqlstatement = "create table if not exist bebidasformatos (id integer primary key, id_bebida integer, id_formato integer)"; if(sqlite3_exec(dienedb, sqlstatement, null, null, &error) == sqlite_ok){ nslog(@"all tables created"); sqlite3_close(dienedb); [self loaddata]; } } } } }else{ nslog(@"unable create table %s", error); } }else{ nslog(@"database exists already"); [self cleardata] } }else{ nslog(@"error opening database"); } }
it crash in second sqlstatement , go the}else{
nslog(@"unable create table %s", error);
but not log anythink
the problem in sql appear first sql statement correctly uses if not exists
, rest use if not exist
.
you're not seeing error message because you're logging errors if first sqlite3_exec
fails. rest of if
statements don't have else
clauses. want nslog
error
each failed sqlite3_exec
call.
alternatively, sqlite3_exec
, unlike other sqlite functions, accepts multiple sql statements, terminated semicolons. simplifying code since 1 sqlite3_exec
, need 1 else
statement:
const char *sqlstatement = "create table if not exists categorias (id integer primary key, nombre text);" "create table if not exists subcategorias (id integer primary key, id_categoria integer, nombre text);" "create table if not exists formatos (id integer primary key, nombre text);" "create table if not exists bebidas (id integer primary key, id_categoria integer, id_subcategoria integer, nombre text, descripcion text, ruta_imagen text);" "create table if not exists bebidasformatos (id integer primary key, id_bebida integer, id_formato integer);"; char *error; if(sqlite3_exec(dienedb, sqlstatement, null, null, &error) == sqlite_ok){ nslog(@"all tables created"); [self loaddata]; } else { nslog(@"unable create table %s", error); sqlite3_free(error); error = null; }
note, i've fixed if not exists
error, above. also, note, if error message, you're responsible freeing sqlite3_free
.
Comments
Post a Comment