Wine Too
Wine Too

Reputation: 4655

Check whether CREATE TABLE actually creates the table or whether it already existed?

I create table in SQLite without checking every time whether it exists.

sqlite3_stmt* create_stmt = NULL;
if (sqlite3_prepare_v2(db, "CREATE TABLE mytable (sif INTEGER PRIMARY KEY, name VARCHAR, description VARCHAR);", -1, &create_stmt, NULL) == SQLITE_OK)
{
    sqlite3_step(create_stmt);
    sqlite3_finalize(create_stmt);
}

If the table doesn't exist, it will be created; if it exists, nothing happens.

I would like to know if there is some way to get information whether the table is created or just checked?

Upvotes: 3

Views: 941

Answers (3)

Takashi
Takashi

Reputation: 31

I'm not sure if you are still looking for an answer but if the table already exists then sqlite3_finalize returns non zero (not SQLITE_OK) value.

Upvotes: 3

Coren
Coren

Reputation: 5637

There's an equivalent to mysql's describe table in sqlite3 : .schema TABLENAME. See this question for more info about it.

So you can issue a .schema mytable in order to know if it's been created and what it looks like. In order to be more focused on a single table, you can also use this statement :

select count(type) from sqlite_master where type='table' and name='TABLE_NAME_TO_CHECK';

Upvotes: 2

Torp
Torp

Reputation: 7924

If i recall correctly, in case your table already exists it will be sqlite3_step() that fails, not sqlite3_prepare_v2. Check the result for that too.
Edit: Besides you should check it all the time anyway, to catch corrupted databases or other error conditions ;)

Upvotes: 1

Related Questions