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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
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() |