How to check if table exists in sqlite3 C ++ API?

I open a database file and potentially create it if it does not exist.

But for some reason this does not create a table. Any ideas?

const char* sql = "CREATE TABLE IF NOT EXISTS blocks(id text primary_key,length numeric)"; sqlite3_stmt *stmt; rc = sqlite3_prepare_v2(db_, create_table_sql, -1, &stmt, NULL); rc = sqlite3_step(stmt); 

I don’t have it, yes, I check the return code at every point. There are no errors.

Perhaps there is a better way to do this?

+7
c ++ sqlite3
source share
4 answers

Change to another given answer:

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

Will return 0, the table does not exist, 1 if it is.

+9
source share

Run the following SQL:

 select 1 from sqlite_master where type='table' and name='TABLE_NAME_TO_CHECK' 

If you get a row, then the table exists. If the result set is empty, then this is not the case.

+5
source share

It looks like you are missing the correct parenthesis in SQL. It should be:

 const char* sql = "CREATE TABLE IF NOT EXISTS blocks(id text primary_key,length numeric);"; 
+2
source share

Answering my own question.

This is not actually reflected in the code above. It actually worked. But I had a typo in the database that I used. Therefore, when I examined it using the sqlite3 command-line tool, it did not contain a table or the expected data.

However, I am curious if there is a function that will allow me to check if the table exists or not.

0
source share

All Articles