user9767519
user9767519

Reputation:

How do I create a foreign key in sqlite3 python

I can't get my program to use a foreign key for some unbeknown reason. I have read other questions related to this but cant find an answer that works. I tried the PRAGMA foreign_keys = ON, but instead i get a syntax error for "foreign_keys". I also tried removing this and running the program again and instead got an error saying the column I'm trying to create doesn't exist

import sqlite3
import os
import random
from tkinter import *
import uuid
PRAGMA foreign_keys = ON

conn = sqlite3.connect('MyComputerScience.db')
c = conn.cursor() 
c.execute("""CREATE TABLE IF NOT EXISTS users (
            UserID text PRIMARY KEY,
            FName text,
            SName text,
            username text,
            password varchar,
            userType text)""")

c.execute("""CREATE TABLE IF NOT EXISTS classes (
            ClassID PRIMARY KEY,
            FOREIGN KEY (User) REFERENCES users(UserID)))""")





 FOREIGN KEY (User) REFERENCES users(UserID)))""")
sqlite3.OperationalError: unknown column "User" in foreign key definition

Upvotes: 1

Views: 2446

Answers (2)

Tony
Tony

Reputation: 10327

You need to create the fields in the table before using them as a foreign key.

As you did not add a field User to your table, you got the error:

unknown column "User" in foreign key definition

To fix the error, add User to your table definition

c.execute("""CREATE TABLE IF NOT EXISTS classes (
            ClassID PRIMARY KEY,
            User text,
            FOREIGN KEY (User) REFERENCES users(UserID)))""")

However, I would question the design. The table classes would only be able to relate one user per class. Is that what you want to do?

Upvotes: 1

Kostas Charitidis
Kostas Charitidis

Reputation: 3103

c.execute("""CREATE TABLE IF NOT EXISTS classes (
            ClassID PRIMARY KEY,
            FOREIGN KEY (ClassID) REFERENCES users(UserID)))""")

That's the correct syntax but this way you set as foreign key your primary key. Maybe you wanted to use another field.

Upvotes: 0

Related Questions