Python Forum
FOREIGN KEY constraint failed
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
FOREIGN KEY constraint failed
#1
Hello, I am trying to work with foreign keys in databases for the first time but every time I run my code I get the same error:
FOREIGN KEY constraint failed
I am taking this code right out of my textbook so I can run it on my own, so this is not homework. I'm just trying to study but I can't figure out why I am getting this error. Can you please look at my code and help me?
import sqlite3


def main():
    conn = None
    try:
        # connect to the database and get cursor
        conn = sqlite3.connect('employees.db')
        cur = conn.cursor()

        # enable foreign key
        cur.execute('PRAGMA foreign_keys=ON')

        # add the tables
        cur.execute('''CREATE TABLE Departments (DepartmentID INTEGER PRIMARY KEY NOT NULL,
            DepartmentName TEXT)''')
        cur.execute('''CREATE TABLE Locations (LocationID INTEGER PRIMARY KEY NOT NULL,
            City TEXT)''')
        cur.execute('''CREATE TABLE Employees (EmployeeID INTEGER PRIMARY KEY NOT NULL,
            Name TEXT,
            Position TEXT,
            DepartmentID INTEGER,
            LocationID INTEGER,
            FOREIGN KEY(DepartmentID) REFERENCES Departments(DepartmentID),
            FOREIGN KEY(LocationID) REFERENCES Locations(LocationID))''')

        # add rows to Employees table
        cur.execute('''INSERT INTO Employees (Name, Position, DepartmentID, LocationID)
         VALUES("Arlene Meyers", "Director", 4, 4),
         ("Janelle Grant", "Engineer", 2, 1),
         ("Jack Smith", "Manager", 3, 3),
         ("Sonia Alvarado", "Auditor", 1, 2),
         ("Renee Kincaid", "Designer", 3, 3),
         ("Curt Green", "Supervisor", 2, 1)''')

        # add rows to the Departments table
        cur.execute('''INSERT INTO Departments (DepartmentName)
        VALUES ("Accounting"),
        ("Manufacturing"),
        ("Marketing"),
        ("Research and Development")''')

        # add row to the Locations table
        cur.execute('''INSERT INTO Locations (City)
        VALUES ("Austin"),
        ("Boston"),
        ("New York City"),
        ("San Jose")''')

        conn.commit()

        print('Employee successfully added.')

    except sqlite3.Error as err:
        print(err)

    finally:
        # if connection is open then close it
        if conn != None:
            conn.close()


if __name__ == '__main__':
    main()
Reply
#2
Insert the departments and the locations before the query to insert the employees and it will work. The queries fail because they use foreign IDs that don't exist yet in the database.
SalsaBeanDip likes this post
Reply
#3
Thank you! That got it to work.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  SQLite Unique constraint failed error djwilson0495 3 13,438 Aug-14-2020, 05:23 PM
Last Post: ndc85430
  length constraint on phrase hash to password javaben 0 1,908 Aug-21-2019, 05:34 PM
Last Post: javaben
  [split] create a virtual keyboard of an unknown foreign language with python fakoly 0 2,386 May-28-2018, 01:34 AM
Last Post: fakoly
  sqlite3 foreign key dsvinson 2 4,547 Mar-31-2018, 04:43 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020