Dec-04-2020, 12:48 AM
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?
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()
