2

I am trying to create a database program using SQLite3 and Tkinter. It is for my Computer Science A-Level Course. I am getting this error whenever I try to run the following code:

Exception has occurred: OperationalError near "BranchID": syntax error File "\Code\tables.py", line 14, in cursor.execute('''

import sqlite3
with sqlite3.connect("LeeOpt.db") as db:
 cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Branches(
BranchID INTEGER PRIMARY KEY,
Town VARCHAR(30) NOT NULL,
Postcode VARCHAR(8) NOT NULL,
Email VARCHAR(30) NOT NULL,
Telephone VARCHAR(15) NOT NULL);
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS Customer(
CustomerID INTEGER PRIMARY KEY,
BranchID INTEGER NOT NULL,
Name VARCHAR(20) NOT NULL,
Surname VARCHAR(30) NOT NULL,
DateOfBirth NOT NULL,
Town VARCHAR(30) NOT NULL,
Postcode VARCHAR(7) NOT NULL,
EmailAddress VARCHAR(30) NOT NULL,
TelephoneNo VARCHAR(12) NOT NULL,
MedicalConditions TEXT,
FOREIGN KEY BranchID REFERENCES Branches(BranchID));
''')

I am struggling to understand what has went wrong. Could anyone help me solve this problem? Thanks.

Delrius Euphoria
15.1k3 gold badges20 silver badges53 bronze badges
asked Nov 2, 2020 at 15:07
1
  • 1
    Is your indentation like that in the file or is your question wrong? Commented Nov 2, 2020 at 15:12

1 Answer 1

1

I think the error was more with indentation, try this:

cursor.execute('''
CREATE TABLE IF NOT EXISTS Branches(
BranchID INTEGER PRIMARY KEY,
Town VARCHAR(30) NOT NULL,
Postcode VARCHAR(8) NOT NULL,
Email VARCHAR(30) NOT NULL,
Telephone VARCHAR(15) NOT NULL);''') # moved the triple quote together with the same line
cursor.execute('''
CREATE TABLE IF NOT EXISTS Customer(
CustomerID INTEGER PRIMARY KEY,
BranchID INTEGER NOT NULL,
Name VARCHAR(20) NOT NULL,
Surname VARCHAR(30) NOT NULL,
DateOfBirth NOT NULL,
Town VARCHAR(30) NOT NULL,
Postcode VARCHAR(7) NOT NULL,
EmailAddress VARCHAR(30) NOT NULL,
TelephoneNo VARCHAR(12) NOT NULL,
MedicalConditions TEXT,
FOREIGN KEY(BranchID) REFERENCES Branches(BranchID));''') #made proper syntax changes here 

Just googling syntax for FOREIGN KEY got me this:

FOREIGN KEY(columnname) REFERENCES tablename(columnname)

So you forgot to enclose the BranchID in ().

answered Nov 2, 2020 at 18:01
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.