Using foreign keys in sqlite3 for Python

后端 未结 3 549
孤独总比滥情好
孤独总比滥情好 2021-02-12 23:24

I\'m writing a program that creates a sqlite3 database through python. I have one table of Authors (AuthorID, Name) and a second table of books (BookID, Title, AuthorID) I\'ve c

3条回答
  •  被撕碎了的回忆
    2021-02-13 00:09

    So to do what you want to do you need to create one database file with 2 tables.

    Example:

    conn=sqlite3.connect("clientdatabase.db")
    conn.execute("PRAGMA foreign_keys = 1")
    cur=conn.cursor()
    
    # Create 2 tables if they don't exist: Clients and Work_Done
    cur.execute('''CREATE TABLE IF NOT EXISTS Clients
    (CID INTEGER PRIMARY KEY,
    First_Name  TEXT    NOT NULL,
    Last_Name       TEXT,
    Business_Name   TEXT,
    Phone           TEXT,
    Address         TEXT,
    City            TEXT,
    Notes           TEXT,
    Active_Status   TEXT    NOT NULL)''')      
    
    cur.execute('''CREATE TABLE IF NOT EXISTS Work_Done
    (ID INTEGER PRIMARY KEY,
    Date            TEXT    NOT NULL,
    Onsite_Contact  TEXT,
    Work_Done       TEXT    NOT NULL,
    Parts_Installed TEXT,
    Next_Steps      TEXT,
    CID             INT,
    FOREIGN KEY (CID) REFERENCES CLIENTS (CID))''')
    conn.commit()
    

    Note that both tables are in the same database and you add the line after connection and before the cursor object.

    Hope this helps.

提交回复
热议问题