簡體   English   中英

創建表時我的python + sqlite3代碼有什么問題?

[英]What's wrong with my python + sqlite3 code in creating tables?

我正在嘗試使用sqlite3使用外鍵創建具有多個相互連接的表的數據庫,並且我正在用python編寫。

這是我的代碼:

db = sqlite3.connect("PHLC.db")
cur = db.cursor()

# ############################
# delete original table if exist
# drop from the end (foreign key issue)
cur.execute("drop table if exists measurement")
cur.execute("drop table if exists mouse")
cur.execute("drop table if exists drug")
cur.execute("drop table if exists batch")
cur.execute("drop table if exists phlc")

# ############################
# create table
# ############################
# 1. phlc
cur.execute(
    """
    CREATE TABLE phlc (
    phlc_id INTEGER NOT NULL PRIMARY KEY,
    cancer VARCHAR(30) NOT NULL,
    histology VARCHAR(60) NOT NULL
    )
    """
)
# 2. batch
cur.execute(
    """
    CREATE TABLE batch (
    batch_id INTEGER PRIMARY KEY AUTOINCREMENT,
    phlc_id INTEGER NOT NULL,
    FOREIGN KEY (phlc_id) REFERENCES phlc (phlc_id),
    batch_number INTEGER NOT NULL
    )
    """
)
# 3. drug
cur.execute(
    """
    CREATE TABLE drug (
    drug_id INTEGER PRIMARY KEY AUTOINCREMENT,
    drug_name VARCHAR(30) NOT NULL,
    batch_id INTEGER NOT NULL,
    FOREIGN KEY (batch_id) REFERENCES batch (batch_id)
    )
    """
)
# 4. mouse
cur.execute(
    """
    CREATE TABLE mouse (
    mouse_id INTEGER PRIMARY KEY AUTOINCREMENT,
    drug_id INTEGER NOT NULL,
    FOREIGN KEY (drug_id) REFERENCES drug (drug_id)
    )
    """
) 
# 5. measurement
cur.execute(
    """
    CREATE TABLE measurement (
    measurement_index INTEGER PRIMARY KEY AUTOINCREMENT,
    mouse_id INTEGER NOT NULL,
    FOREIGN KEY (mouse_id) REFERENCES mouse (mouse_id),
    day INTEGER NOT NULL,
    tumor_volume FLOAT NOT NULL,
    comment VARCHAR(255) NULL
    )
    """
) 

db.commit()
db.close()

我得到的錯誤是在批處理表:

sqlite3.OperationalError: near "batch_number": syntax error

有人可以指出代碼的問題嗎? (它與MySQL配合良好。)

根據文檔 ,所有表約束必須位於所有列定義之后:

CREATE TABLE batch (
    batch_id INTEGER PRIMARY KEY AUTOINCREMENT,
    phlc_id INTEGER NOT NULL,
    batch_number INTEGER NOT NULL,
    FOREIGN KEY (phlc_id) REFERENCES phlc (phlc_id)
)

或者,使外鍵聲明成為列約束:

CREATE TABLE batch (
    batch_id INTEGER PRIMARY KEY AUTOINCREMENT,
    phlc_id INTEGER NOT NULL REFERENCES phlc (phlc_id),
    batch_number INTEGER NOT NULL
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM