sqlite3.IntegrityError: Datatype Missmatch - python

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).

Related

Attempted to autoincrement an integer value but returend null, how do I fix?

tblcustomer = """ CREATE TABLE IF NOT EXISTS Customer
(
CustomerID INT,
CustomerName TEXT,
Address TEXT,
Postcode TEXT,
EmailAddress TEXT,
primary key(CustomerID AUTOINCREMENT)
)"""
cursor.execute(tblcustomer)
connection.commit()
This is my table (I'm using sqlite3), but it returns 'null' to the table values. For my user inputs I just asked for the other 4 values and inserted them into the table, omitting 'CustomerID'. How do I fix it so it actually autoincrements?
Here's how you can modify your table to include an AUTOINCREMENT column for the CustomerID field:
CREATE TABLE IF NOT EXISTS Customer(
CustomerID INTEGER PRIMARY KEY AUTOINCREMENT,
CustomerName TEXT,
Address TEXT,
Postcode TEXT,
EmailAddress TEXT)

How do I deal with non deterministic value in SQLite3?

Below you can see the tables in my sqlite3 database:
songs
files
tags
playlists
These are the relationships between the tables:
One To One: Songs and files
Many To Many: Songs and tags, Songs and playlists
Below you can see the table queries I am using:
create_songs_table_query = """ CREATE TABLE IF NOT EXISTS songs (
song_id integer PRIMARY KEY AUTOINCREMENT,
title text NOT NULL,
artist text NOT NULL,
added_timestamp integer NOT NULL,
file_id INTEGER NULL,
FOREIGN KEY (file_id)
REFERENCES files (file_id)
ON DELETE CASCADE
); """
create_files_table_query = """ CREATE TABLE IF NOT EXISTS files (
file_id integer PRIMARY KEY AUTOINCREMENT,
filename text NULL,
size integer NULL,
song_id INTEGER NOT NULL,
FOREIGN KEY (song_id)
REFERENCES songs (song_id)
ON DELETE CASCADE
); """
create_tags_table_query = """CREATE TABLE IF NOT EXISTS tags (
tag_id integer PRIMARY KEY AUTOINCREMENT,
tag_text text NOT NULL,
tag_timestamp integer NULL,
); """
create_songs_tags_table_query = """CREATE TABLE IF NOT EXISTS songs_tags (
song_tag_id integer PRIMARY KEY AUTOINCREMENT,
song_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
FOREIGN KEY (song_id)
REFERENCES songs (song_id)
ON DELETE CASCADE,
FOREIGN KEY (tag_id)
REFERENCES tags (tag_id)
ON DELETE CASCADE
); """
create_playlists_table_query = """CREATE TABLE IF NOT EXISTS playlists (
playlist_id integer PRIMARY KEY AUTOINCREMENT,
playlist_title text NOT NULL,
created_timestamp INTEGER NOT NULL,
updated_timestamp INTEGER NULL,
); """
create_songs_playlists__table_query = """CREATE TABLE IF NOT EXISTS songs_playlists (
song_playlist_id integer PRIMARY KEY AUTOINCREMENT,
song_id INTEGER NOT NULL,
playlist_id INTEGER NOT NULL,
FOREIGN KEY (song_id)
REFERENCES songs (song_id)
ON DELETE CASCADE,
FOREIGN KEY (playlist_id)
REFERENCES playlists (playlist_id)
ON DELETE CASCADE
); """
I am trying sucessfully to get the total songs each tag has and order by it:
SELECT tags.tag_id, tags.tag_text, COUNT(tags.tag_id) AS total, tags.included, tags.tag_timestamp
FROM tags
JOIN songs_tags ON tags.tag_id = songs_tags.tag_id
GROUP BY songs_tags.tag_id
ORDER BY total DESC
This is the query to order by tags.tag_text:
SELECT tags.tag_id, tags.tag_text, COUNT(tags.tag_id) AS total, tags.included, tags.tag_timestamp
FROM tags
JOIN songs_tags ON tags.tag_id = songs_tags.tag_id
WHERE tags.included = 1
GROUP BY songs_tags.tag_id
ORDER BY tags.tag_text
I am using Python and Pycharm. Python doesn't return any records and Pycharm shows me the following pop up in the editor window:
Nondeterministic value: column tag_text is neither aggregated, nor mentioned in GROUP BY clause
Although, if I run the query from PyCharm's database console I get the desired results.
It's a bit tricky, any ideas ?
Writer the query correctly, so the SELECT and GROUP BY columns are consistent:
SELECT t.tag_id, t.tag_text, COUNT(*) AS total, t.included, t.tag_timestamp
FROM tags t JOIN
songs_tags st
ON t.tag_id = st.tag_id
WHERE t.included = 1
GROUP BY t.tag_id, t.tag_text, t.included, t.tag_timestamp
ORDER BY t.tag_text;
This also introduced table alias so the query is easier to write and to read.

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)""")

Creating tables in MySQL in Python 3.4

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.

(Python, sqlite3) Building relational database?

I am trying to create a relational database in python with sqlite3. I am a little fussy on how to connect the tables in the database so that one entity connects to another via the second table. I want to be able to make a search on a persons name via a webpage and then find the parents related to that person. Im not sure if I need two tables or three.
This is how my code looks like right now:
class Database:
'''Initiates the database.'''
def __init__(self):
self.db = sqlite3.connect('family2.db')
def createTable(self):
r = self.db.execute('''
CREATE TABLE IF NOT EXISTS family2 (
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
fname TEXT,
sname TEXT,
birthdate TEXT,
deathdate TEXT,
mother TEXT,
father TEXT
)''')
self.db.commit()
g = self.db.execute('''CREATE TABLE IF NOT EXISTS parents(
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
mother TEXT,
father TEXT)''')
self.db.commit()
b = self.db.execute('''CREATE TABLE IF NOT EXISTS relations(
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
family2,
parents TEXT
)''')
self.db.commit()
Thanks in advance!
You don't need multiple tables; you can store the IDs of the parents in the table itself:
CREATE TABLE persons(
id INTEGER PRIMARY KEY,
name TEXT,
mother_id INT,
father_id INT
);
You can then find the mother of a person that is identified by its name with a query like this:
SELECT *
FROM persons
WHERE id = (SELECT mother_id
FROM persons
WHERE name = '...')

Categories

Resources