Check existing tables in sqlite and python?¿ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Check existing tables in sqlite and python?¿

I'm trying to check if a table exists i'm working with sqlite and python i've tried with cursor.execute('''SELECT name FROM sqlite_master WHERE type="table";''') tables = cursor.fetchall() # this return an empty list so: if not tableName in tables: cursor.execute('''CREATE TABLE info( name TEXT, age INTEGER);''') # everything went Ok but if I do this process again this will tell me error because table info already exists. After sometime of searching I found that This will always happen bacause cursor.fetchall() will return [('info',),] and 'info' is not actually in [('info',),] so It gives me a info table already exists. So how Can I do this without getting this problem?

28th Jan 2019, 9:54 AM
Edwing123
Edwing123 - avatar
2 Answers
+ 1
The problem is with your condition: if not tableName in tables: This is wrong because the returned datatype of cursor.fetchall is a list of tuples. You can do something like this instead: cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='info'") if not cursor.fetchall(): cursor.execute("CREATE TABLE info (name TEXT, age INTEGER)") so, if the table does not exist, then indeed cursor.fetchall() will give you an empty list. The boolean value of an empty list is False. so the if condition will evaluate to "not False" which is True. I made also a step-by-step sample code with comments ;) https://code.sololearn.com/csZ5bjiWfdCR/#py
29th Jan 2019, 9:47 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Thnks you Tibor Santa
29th Jan 2019, 12:06 PM
Edwing123
Edwing123 - avatar