PRAGMA外键错误(Python)

PRAGMA外键错误(Python),python,database,python-3.x,sqlite,Python,Database,Python 3.x,Sqlite,将粘贴在整个文件中,因为我完全不知道如何修复我的问题 import sqlite3 import time import datetime import sys conn = sqlite3.connect('offerdatabase1.db') c = conn.cursor() c.execute('PRAGMA foreign_keys = ON') ############################# Creating the Database Tables ######

将粘贴在整个文件中,因为我完全不知道如何修复我的问题

import sqlite3
import time
import datetime
import sys

conn = sqlite3.connect('offerdatabase1.db')

c = conn.cursor()

c.execute('PRAGMA foreign_keys = ON')

############################# Creating the Database Tables #############################

# Creating the 'Odds' Table

def create_odds_table():

    c.execute("""CREATE TABLE IF NOT EXISTS Odds(OddsID INTEGER PRIMARY KEY,
                         TeamSelection TEXT,
                         BackOdds INTEGER,
                         LayOdds INTEGER)
                         """)

    c.execute('PRAGMA foreign_keys = ON')

# # # Creating the 'Value' Table # # #

def create_value_table():

    c.execute("""CREATE TABLE IF NOT EXISTS Value(ValueID INTEGER PRIMARY KEY,
                        BackStake INTEGER,
                        LayStake INTEGER,
                        Liability INTEGER,
                        NetValue INTEGER)

                        """)

    c.execute('PRAGMA foreign_keys = ON')

# Creating the 'User' Table

def create_user_table():

    c.execute("""CREATE TABLE IF NOT EXISTS User(UserID INTEGER PRIMARY KEY,
                        FirstName TEXT,
                        LastName TEXT,
                        Email TEXT,
                        Date TEXT,
                        Time TEXT)
                        """)

    c.execute('PRAGMA foreign_keys = ON')

# Creating the 'Offer' Table

def create_offer_table():

    c.execute("""CREATE TABLE IF NOT EXISTS Offer(OfferID INTEGER PRIMARY KEY,
                        OfferType TEXT,
                        OfferDesc TEXT,
                        Bookmaker TEXT,
                        Exchange TEXT,

                        OddsID INTEGER,
                        ValueID INTEGER,
                        UserID INTEGER,

                        FOREIGN KEY(OddsID) REFERENCES Odds(OddsID),
                        FOREIGN KEY(ValueID) REFERENCES Value(ValueID),
                        FOREIGN KEY(UserID) REFERENCES User(UserID))""")

    c.execute('PRAGMA foreign_keys = ON')

# Running the Subroutines, in order to create the database with tables previously stated.

if __name__ == "__main__":

    db_name = ('offerdatabase1.db')

    c.execute('PRAGMA foreign_keys = ON')

    create_odds_table()

    create_value_table()

    create_user_table()

    create_offer_table()

############################# Inserting Data into Tables #############################

def data_entry_odds():

    print('==================== Odds and Team Selection ====================')

    TeamSelection = input('Team you selected: ')
    BackOdds = input('Back Bet Odds: ')
    LayOdds = input('Lay Bet Odds: ')

    c.execute("INSERT INTO Odds (TeamSelection, BackOdds, LayOdds) VALUES (?, ?, ?)",
              (TeamSelection, BackOdds, LayOdds))

    c.execute('PRAGMA foreign_keys = ON')

    conn.commit()

def data_entry_value():

    print('================ Stakes, Liability and Net Value ================')

    BackStake = input('Stake on Back Bet: ')
    LayStake = input('Stake on Lay Bet: ')
    Liability = input('Liability (applies only with exchange): ')
    NetValue = input('Net value : ')

    c.execute("INSERT INTO Value (BackStake, LayStake, Liability, NetValue) VALUES (?, ?, ?, ?)",
              (BackStake, LayStake, Liability, NetValue))

    c.execute('PRAGMA foreign_keys = ON')

    conn.commit()

def data_entry_user():

    print('======================== User Information =======================')

    FirstName = input('Firstname: ')
    LastName = input('Surname: ')
    Email = input('Email Address: ')
    Date = time.strftime("%d/%m/%Y")
    Time = time.strftime("%H:%M")


    c.execute("INSERT INTO User (FirstName, LastName, Email, Date, Time) VALUES (?, ?, ?, ?, ?)",
              (FirstName, LastName, Email, Date, Time))

    c.execute('PRAGMA foreign_keys = ON')

    conn.commit()

def data_entry_offer():

    print('======================= Offer Information =======================')

    OfferType = input('Type of Offer: ')
    OfferDesc = input('Offer Description: ')
    Bookmaker = input('Name of Bookmaker: ')
    Exchange = input('Name of Exchange: ')

    c.execute("INSERT INTO Offer (OfferType, OfferDesc, Bookmaker, Exchange) VALUES (?, ?, ?, ?)",
              (OfferType, OfferDesc, Bookmaker, Exchange))

    c.execute('PRAGMA foreign_keys = ON')

    conn.commit()

########################### Text Based User Interface ###########################

def rootchoice():

    userchoice = input('Would you like to track a bet? (Y - Yes, N - No) ')

    if userchoice.upper() == 'Y':
        yeschoice()

    elif userchoice.upper() == 'N':
        nochoice()

    else:
        print('*ERROR* - Please enter either \'Y\' or \'N\' (no other characters accepted)')
        rootchoice()

def yeschoice():

    data_entry_user()
    data_entry_offer()
    data_entry_odds()
    data_entry_value()

    print('Data entry complete, recorded successfully.')

    loopchoice()

def nochoice():

    print('Thank you for using James\' Betting Tracker, goodbye!')

    sys.exit()

def loopchoice():

    loopuserchoice = input('Would you like to track another bet? (Y - Yes, N - No) ')

    if loopuserchoice.upper() == 'Y':
        yeschoice()

    elif loopuserchoice.upper() == 'N':
        nochoice

    else:
        print('*ERROR* - Please enter either \'Y\' or \'N\' (no other characters accepted)')
        loopchoice()

print('Welcome to James\' Betting Tracker!')
rootchoice()
请原谅这些注释和荒谬的标题,我是为一个学校项目写这段代码的。在阅读了sqlite3中的外键主题之后,我偶然发现了这个命令

PRAGMA foreign_keys = ON
在阅读了相关内容后,我被告知每次建立数据库连接时都必须将PRAGMA foreign_键设置为

我已经这样做了,但是外键仍然不能与我的数据库一起工作

任何帮助都将不胜感激,我是python和编程领域的新手,谢谢

被称为“约束”,因为它们是约束,即约束数据库中的值。换句话说,它们阻止您插入违反规则的值

在这种情况下,如果您试图将无效的
OddsID
ValueID
UserID
编号(父表中不存在的编号)插入
Offers
表,则会出现错误。 但你从来没有这样做过;您将这些列留空

数据库不可能自动插入对父表中某一行的引用—应选择这些行中的哪一行


如果您的数据模型要求所有的
提供
行对其他三个表都有有效的引用,请向这些列添加NOTNULL约束。

在调用
connect()
后立即删除所有pragma之外的pragma。然后删除数据库文件,然后重试。(而且“不工作”不是正确的错误描述。)除了第三行的pragma之外,我已经删除了所有pragma(我想这也是您提到的pragma),我也遇到了同样的问题。通过SQL数据库浏览器查看创建的数据库时,所有外键字段仍显示为NULL。如果我尝试将“NOT NULL”约束添加到“Offer”表中的所有相关列,则会出现相同的问题。只是抛出一个错误,说NOTNULL约束失败,执行停止。这种行为就是NOTNULL约束的目的。请看我回答的第三段。