PRAGMA外键错误(Python)

时间:2017-02-10 09:27:40

标签: 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 #############################

# 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_keys设置为ON。

我已经完成了这项工作,但外键仍无法使用我的数据库。

非常感谢任何帮助,对于python和编程的世界来说,我是非常新的,谢谢!

1 个答案:

答案 0 :(得分:0)

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

在这种情况下,如果您尝试插入无效的OddsIDValueIDUserID号码(父表中不存在的号码),则会收到错误Offers表。 但你永远不会这样做;你把这些列留空了。

数据库无法自动插入对父表中某行的引用 - 它应该选择哪一行?

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