Creating tables in MySQL in Python 3.4 - python

I am running a server through Apache using Python 3.4 as a cgi and a MySQL database server on Windows 10. When I try to run my function for creating the database I get the error:
DatabaseError: 1005 (HY000): Can't create table `testdb`.`studentexam` (errno: 150
"Foreign key constraint is incorrectly formed")
The function for creating the database
import mysql.connector as conn
#connect to server
db=conn.connect(host="localhost",user="root",password="")
cursor=db.cursor()
#create database
cursor.execute("""CREATE DATABASE IF NOT EXISTS Testdb""")
db.commit()
#use database
cursor.execute("""USE Testdb""")
db.commit()
#create Teacher table
cursor.execute("""CREATE TABLE IF NOT EXISTS Teacher(
TeacherUsername VARCHAR(255) PRIMARY KEY,
TeacherPassword TEXT)""")
db.commit()
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentNo INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create exam table
cursor.execute("""CREATE TABLE IF NOT EXISTS Exam(
TestName VARCHAR(255) PRIMARY KEY,
TestTotalMarks TEXT,
Teacher VARCHAR(255),
FOREIGN KEY(Teacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create StudentExam table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentExam(
TestName VARCHAR(255),
StudentID INT,
StudentTotalMarks INT,
PRIMARY KEY(TestName,StudentID),
FOREIGN KEY(TestName) REFERENCES Exam(TestName),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create ExamSection table
cursor.execute("""CREATE TABLE IF NOT EXISTS ExamSection(
TestName VARCHAR(255),
SectionID INT,
PRIMARY KEY(TestName,SectionID),
FOREIGN KEY(TestName) REFERENCES Exam(TestName),
FOREIGN KEY(SectionID) REFERENCES Section(SectionID))""")
db.commit()
#create Section table
cursor.execute("""CREATE TABLE IF NOT EXISTS Section(
SectionID INT PRIMARY KEY,
SectionName TEXT,
SectionTotalMarks INT)""")
db.commit()
#create Question table
cursor.execute("""CREATE TABLE IF NOT EXISTS Question(
QuestionID INT PRIMARY KEY,
SectionID VARCHAR(255),
Image TEXT,
Question TEXT,
PossibleAnswer TEXT,
CorrectAnswer TEXT,
QuestionType TEXT,
FOREIGN KEY(SectionID) REFERENCES Section(SectionID))""")
db.commit()
#create QuestionResults Table
cursor.execute("""CREATE TABLE IF NOT EXISTS QuestionResults(
QuestionID INT,
StudentID INT,
SectionID VARCHAR(255),
StudentAnswer TEXT,
PRIMARY KEY(QuestionID,StudentID),
FOREIGN KEY(QuestionID) REFERENCES Question(QuestionID)
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create Revision table
cursor.execute("""CREATE TABLE IF NOT EXISTS Revision(
RevisionID INT PRIMARY KEY,
RevisionSheet TEXT,
TeacherUsername VARCHAR(255),
FOREIGN KEY(TeacherUsername) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create StudentRevition table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentRevision(
RevisionID INT,
StudentID INT,
PRIMARY KEY(RevisionID,StudentID),
FOREIGN KEY(RevisionID) REFERENCES Revision(RevisionID),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create StudentResults table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentResults(
SectionID VARCHAR(255),
StudentID INT,
StudentSectionMarks INT,
PRIMARY KEY(SectionID,StudentID),
FOREIGN KEY(SectionID) REFERENCES Section(SectionID),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
cursor.close()
EDIT: I Changed StudentNo to StudentID and now get the error:
DatabaseError: 1005 (HY000): Can't create table `testdb`.`examsection` (errno: 150
"Foreign key constraint is incorrectly formed")

Change this:
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentNo INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
to this:
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentID INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()

When creating StudentExam, you are referencing Student.StudentId which doesn't exist. It looks like you rather want to reference Student.StudentNo.
edit:
When you create ExamSection, you reference the Section table, which doesn't exist yet. Move the Section creation state up so that it runs and commits before you create ExamSection.

Related

sqlite3.IntegrityError: Datatype Missmatch

When I run my code, i am getting an error saying "sqlite3.IntegrityError: Datatype Mismatch". I believe it's something to do with database but I can't seem to find the error. I checked if i have let a foreign key of a particular datatype reference an attribute of a different datatype but still can't find the error. Here is my database:
import sqlite3
connection = sqlite3.connect('database.db')
cursor = connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS tblCustomer (
customerID TEXT (6),
firstName TEXT (10),
secondName TEXT (15),
dob DATE,
address TEXT,
telephone INT (11),
primary key (customerID)
)""")
tblCustomer = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblEmployee (
employeeID TEXT (6),
firstName TEXT (10),
secondName TEXT (15),
dob DATE,
address TEXT,
telephone INT (11),
gender TEXT,
role TEXT,
salary INT,
primary key (employeeID)
)""")
tblEmployee = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblBooking (
bookingID TEXT (6),
checkInDate DATE,
checkOutDate DATE,
numberOfOccupants INT,
customerID TEXT,
roomID TEXT,
primary key (bookingID),
foreign key (customerID) REFERENCES tblCustomer(customerID),
foreign key (roomID) REFERENCES tblRoomAllocation(roomID)
)""")
tblBooking = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblRoomAllocation (
roomID TEXT (6),
roomType TEXT (20),
DateAdded DATE,
DateVacated DATE,
housekeepingID TEXT,
primary key (roomID),
foreign key (housekeepingID) REFERENCES tblHousekeeping(housekeepingID)
)""")
tblRoomAllocation = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblHousekeeping (
housekeepingID TEXT (6),
dob DATE,
assignedTo TEXT (20),
primary key (housekeepingID)
)""")
tblHousekeeping = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblPayment (
paymentID TEXT (6),
dob DATE,
amountPaid CURRENCY,
customerID TEXT (6),
primary key (paymentID),
foreign key (customerID) REFERENCES tblCustomer(customerID)
)""")
tblPayment = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblOrder(
orderID TEXT (6),
price CURRENCY,
customerID TEXT (6),
treatmentID TEXT (6),
primary key (orderID),
foreign key (customerID) REFERENCES tblCustomer(customerID),
foreign key (treatmentID) REFERENCES tblTreatment(treatmentID)
)""")
tblOrder = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblTreatment(
treatmentID TEXT (6),
treatmentType TEXT (20),
extras TEXT(20),
employeeID TEXT (6),
primary key (treatmentID),
foreign key (employeeID) REFERENCES tblEmployee(employeeID)
)""")
tblTreatment = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblUser (
userID TEXT (6),
firstName TEXT (10),
secondName TEXT (15),
username VARCHAR(20),
password VARCHAR (20),
primary key (userID)
)""")
tblUser = []
SQLite does not support DATE data type.
See what is supported:
https://www.sqlite.org/datatype3.html
Try using an INTEGER (store unix timestamp), or a TEXT (for iso8601 date).

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails That I can't fix

I am getting this error :
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint
fails (\`GTFS\`.\`#sql-37d_16\`, CONSTRAINT \`#sql-37d_16_ibfk_1\` FOREIGN KEY
(\`service_id\`) REFERENCES \`calendar\` (\`service_id\`))
I'm trying to create my database tables with python , this is what i've tried :
mycursor.execute("CREATE TABLE IF NOT EXISTS routes(route_id varchar(3) PRIMARY KEY, agency_id varchar(2) ,route_short_name varchar(20) ,route_long_name varchar(50) ,route_desc varchar(30) ,route_type varchar(30) ,route_url varchar(30) ,route_color varchar(30) ,route_text_color varchar(30)) ")
mycursor.execute("CREATE TABLE IF NOT EXISTS calendar (service_id varchar(4) PRIMARY KEY,monday varchar(4) ,tuesday varchar(4) ,wednesday varchar(4) ,thursday varchar(4) ,friday varchar(4) ,saturday varchar(4) ,sunday varchar(4) ,start_date varchar(8) ,end_date varchar(8)) ")
mycursor.execute("CREATE TABLE IF NOT EXISTS trips (route_id varchar(3) ,service_id varchar(4) ,trip_id varchar(6) PRIMARY KEY,trip_headsign varchar(20) ,trip_short_name varchar(3) ,direction_id varchar(1) ,block_id varchar(1) ,shape_id varchar(5) )")
mycursor.execute("ALTER TABLE trips ADD FOREIGN KEY (service_id) REFERENCES calendar(service_id); ")
mycursor.execute("ALTER TABLE trips ADD FOREIGN KEY (route_id) REFERENCES routes(route_id); ")
I'm expecting to insert into my table some data provided in a list but i always get this error in my terminal
Because some values for trips.service_id column don't exist in the parent(calendar) table for the common column service_id.
You may try to insert those values by such a insert statement :
insert into calendar(...,service_id,...)
select ...,service_id,...
from trips t
where not exists ( select 0 from calendar where service_id=t.service_id );
before adding the constraint by
ALTER TABLE trips ADD FOREIGN KEY (service_id) REFERENCES calendar(service_id);

Python SQLite3 function not printing any data

I have created a function that is supposed to send all the items, with a stock level of less than 10, in my database to a text file. But i am not receiving any data when I press the reorder button.
def Database():
global conn, cursor
conn = sqlite3.connect("main_storage.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS `admin` (admin_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT, password TEXT)")
cursor.execute("CREATE TABLE IF NOT EXISTS `product` (product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, product_name TEXT, product_qty TEXT, product_price TEXT)")
cursor.execute("CREATE TABLE IF NOT EXISTS `basket` (product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, product_name TEXT, product_qty TEXT, product_price TEXT)")
cursor.execute("SELECT * FROM `admin` WHERE `username` = 'admin' AND `password` = 'admin'")
if cursor.fetchone() is None:
cursor.execute("INSERT INTO `admin` (username, password) VALUES('admin', 'admin')")
conn.commit()
def reorder():
global items
Database()
cursor.execute("SELECT `product_name` FROM `product` WHERE `product_qty` <= 10")
items = cursor.fetchall()
print(items)
cursor.close()
conn.close()
I expect the output to be an array of items within my database e.g. [44, 'motherboard', 9, 80] where 44 is product_id, motherboard is product_name, 9 is product_stock and 80 is product_price. I am actually getting an array with nothing in like: []
product_qty is defined as a TEXT column, so comparisons like <= will be performed between the string values of operands. This may not give the results that you expect:
>>> '8' < '10'
False
Recreate your tables with INTEGER or REAL as the column type for numeric values to get the behaviour that you want. For example:
cursor.execute("""CREATE TABLE IF NOT EXISTS `product` """
"""(product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"""
"""product_name TEXT, product_qty INTEGER, product_price REAL)""")

Missing Index Constraint Adding Foreign Key

I am trying to define the foreign key in the leaderinfo table as UserID, which is the primary key in the usercredentials table.
USERtable="CREATE TABLE IF NOT EXISTS usercredentials (userID VARCHAR(255),username VARCHAR(255),password VARCHAR(255),stakeholder VARCHAR(255))"
mycursor.execute(USERtable)
LEADERtable="""CREATE TABLE IF NOT EXISTS leaderinfo (leaderID VARCHAR(255),firstname VARCHAR(255),secondname VARCHAR(255),age VARCHAR(255), \
gender VARCHAR(255),ethnicity VARCHAR(255),address VARCHAR(255),postcode VARCHAR(255),telephone VARCHAR(255), \
email VARCHAR(255),userID VARCHAR(255),PRIMARY KEY(leaderID),FOREIGN KEY(userID) REFERENCES usercredentials(userID) on update cascade on delete cascade)"""
Error Code:
mysql.connector.errors.DatabaseError: 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'leaderinfo_ibfk_1' in the referenced table 'usercredentials'
The column you are referencing in the leader table isn't indexed. You can fix this by making the userID column a primary key (I'm going to wrap the SQL here for readability):
USERtable="CREATE TABLE IF NOT EXISTS usercredentials (
userID VARCHAR(255),
username VARCHAR(255),
password VARCHAR(255),
stakeholder VARCHAR(255),
PRIMARY KEY(userID))"

How to create unique rows in a table?

I`m just started to learn SQLite. I use python.
The question is how to create rows in tables, so that they are uniqe by name and how to use (extract) id1 and id2 to insert them into a separate table.
import sqlite3
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
id1 integer primary key autoincrement, name)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
id2 integer primary key autoincrement, name)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT INTO table2 VALUES (null, "The Invention of Wings")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
c.execute('INSERT INTO table1 VALUES (null, "Colleen Hoover")')
c.execute('INSERT INTO table2 VALUES (null, "Maybe Someday")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
Thanks.
I think you have some problems with the table creation. I doubt that it worked, because the name columns don't have a type. They should probably be varchar of some length. The JOIN table definition isn't right, either.
CREATE TABLE IF NOT EXISTS table1 (
id1 integer primary key autoincrement,
name varchar(80)
);
CREATE TABLE IF NOT EXISTS table2 (
id2 integer primary key autoincrement,
name varchar(80)
);
CREATE TABLE IF NOT EXISTS t1_t2 (
id1 integer,
id2 integer,
primary key(id1, id2),
foreign key(id1) references table1(id1),
foreign key(id2) references table2(id2)
);
I would not create the tables in code. Script them, execute in the SQLite admin, and have the tables ready to go when your Python app runs.
I would think much harder about your table names if these are more than examples.
I found the problem of unique names on unique column problem.
Actually, I should change INSERT to INSERT OR IGNORE
import sqlite3
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
id1 integer primary key autoincrement, name TEXT unique)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
id2 integer primary key autoincrement, name TEXT unique)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT OR IGNORE INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT OR IGNORE INTO table2 VALUES (null, "The Invention of Wings")')

Categories

Resources