アメグラ2号のブログ

1980年代後半の古き良きビデオゲームのほか、オッサンの個人的備忘録

python sqlite3 SQL文に変数を使う<テーブル有無チェック>

sqlite3でテーブル有無のチェックをする場合。

からっぽかどうかをチェックしてから、createする流れ。

class DBconnection:
    def __init__(self,dbname):
        """
        ///データベース接続///
        """
        self.connection = sqlite3.connect(dbname)
        self.cur = self.connection.cursor()

    def CheckTableExistence(self,tablename):
        """
        ///DB内のテーブル名有無をチェック
        """
        r = self.cur.execute('SELECT COUNT(*) FROM sqlite_master WHERE TYPE="table" AND NAME="%s"' % tablename)
        return r


"""
///テーブル有無チェック後、テーブルを作る
"""
dbc = DBconnection(dbname)
cur = dbc.CheckTableExistence(tablename)

# Check the Existence of table and Create the table
if cur.fetchone() == (0,):
    print("Table is not existed then created")
    # ここでテーブル作成するとか