简体   繁体   English

如何在sqlite3 python中创建外键

[英]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". 我尝试了PRAGMA foreign_keys = ON,但是却收到“ 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
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. 也许您想使用另一个字段。

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: 由于没有在表中添加User字段,因此出现错误:

unknown column "User" in foreign key definition 外键定义中的未知列“ User”

To fix the error, add User to your table definition 要解决该错误,请将“ User添加到表定义中

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. 这些表classes只能与一个类关联一个用户。 Is that what you want to do? 那是你想做的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM