最後更新日期:2025 年 02 月 21 日

這需要用到 sqlite3 中的一個特殊資料表 sqlite_master。

sqlite_master 的結構如下:

CREATE TABLE sqlite_master (
  type TEXT,
  name TEXT,
  tbl_name TEXT,
  rootpage INTEGER,
  sql TEXT
);

type 的值恆為 table,所以如果我們要查詢是否有 categories 這個資料表,就可以用以下 SQL 指令完成。

SELECT * FROM sqlite_master WHERE type = 'table' AND name = "categories"
import sqlite3

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

table_name = 'categories'

# 資料表尚未建立時的檢查
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 categories (
                id integer
                name text)'''
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()

參考資料

https://www.runoob.com/sqlite/sqlite-tutorial.html

Last modified: 2025-02-21

Author

Comments

Write a Reply or Comment

Your email address will not be published.