import sqlite3

conn = sqlite3.connect("test.db")
cursor = conn.cursor()

table_name = 'fruits'

# 資料表尚未建立時的檢查
print("== Check before create table ==")
query_sql = "SELECT * FROM sqlite_master WHERE type = 'table' AND name = ?"
listOfTable = cursor.execute(query_sql, (table_name,)).fetchall()
if listOfTable == []:
    print("Table %s Not exists\n" % table_name)
else:
    print("Table %s exists\n" % table_name)

# 如果資料表不存在,就建立資料表
print("== Create table ==")
create_sql = '''CREATE TABLE IF NOT EXISTS fruits (
                name text, 
                price integer )'''
cursor.execute(create_sql)

# 資料表建立後的檢查
print("== Check after create table ==")
query_sql = "SELECT * FROM sqlite_master WHERE type = 'table' AND name = ?"
listOfTable = cursor.execute(query_sql, (table_name,)).fetchall()
if listOfTable == []:
    print("Table %s Not exists" % table_name)
else:
    print("Table %s exists" % table_name)

conn.commit()
cursor.close()
conn.close()
Last modified: 2022-01-03

Author

Comments

Write a Reply or Comment

Your email address will not be published.