mercredi 17 février 2016

How can I check if a database table exists or not with Python?

I would like to check if a database table exists or not, but I don't know how to do.

I wrote (for example with SQLite, although I use MySQL mainly),

import sqlite3
table_name = "some_table"
connection = sqlite3.connect(db)
cursor = connection.cursor()
table_check = "SELECT name FROM sqlite_master WHERE type='table' AND name={};".format(table_name)
if not cursor.execute(table_check).fetchone():  # if the table doesn't exist
# OR if cursor.execute(table_check).fetchone() == "":
    create_table()
else:
    update_table()

But, an Error occured and I cannot proceed.

sqlite3.OperationalError: no such column: some_table

I read several Q&A here, but I couldn't get those. Any advice can help me. Thank you.

Python 3.5.1

Aucun commentaire:

Enregistrer un commentaire