sqlite3 interface error when binding parameter 1 - python

I am trying to check if a class exists within a "classinfo" database and based on whether it exists or not, will add the details of the class to the database. However, I keep getting and error saying that the parameters for one of the values isnt right.
c.execute("""CREATE TABLE IF NOT EXISTS users (
UserID text PRIMARY KEY,
FName text,
SName text,
username text,
password varchar,
userType text)""")
c.execute("""CREATE TABLE IF NOT EXISTS ClassInfo (
ClassID text PRIMARY KEY,
ClassName text,
Teacher text,
FOREIGN KEY("Teacher") REFERENCES "users"("UserID"));""")
conn.commit()
conn = sqlite3.connect('MyComputerScience.db')
c = conn.cursor()
ClassName = (var_classname.get())
c.execute("SELECT * FROM classinfo WHERE ClassName = ?", (ClassName,))
data = c.fetchall()
if len(data) == 0:
ClassID = str(uuid.uuid4()).replace('-','')
c.execute("SELECT * FROM ClassInfo WHERE ClassID = ?", (ClassID,))
bruh = c.fetchall()
if len(bruh) == 0:
var_insert_classinfo = (ClassID, var_classname, username)
c.execute('insert INTO ClassInfo (ClassID, ClassName, Teacher)VALUES(?,?,?);', var_insert_classinfo,)
conn.commit()
Label(screen6, text = "Successfully registered! Class name is "+ClassName+"", fg = "GREEN", font = ("Calibri",12)).pack()
c.execute('insert INTO ClassInfo (ClassID, ClassName, Teacher)VALUES(?,?,?);', var_insert_classinfo,)
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.

Related

"Delete from" deletes everything

I have a python function that deletes a row in mysql table using name attribute as a condition:
def delete(table: str, name: str):
cursor.execute(f"DELETE FROM {table} WHERE name = {name}")
conn.commit()
I have one row with a name attribute equal to "Name". When I use this function with "Name" it deletes every single row in a table.
I'm guessing that it has to do with passed string being same as attribute. But what would be the solution to that problem except renaming attributes?
So for one, I think you are missing quotes around name, as well as a semicolon.
For further reading you should also take a look at Python parameterized query and Prepared Statement
I do agree with the comments, that table should not be an injected argument for security reasons!
def delete(table: str, name: str):
query = f"DELETE FROM {table} WHERE name = ?"
print(query)
cursor.execute(query, (name,))
conn.commit()`
EDIT FULL WORKING EXAMPLE:
import sqlite3
conn = sqlite3.connect("test")
query_create = '''CREATE TABLE IF NOT EXISTS projects (
id integer PRIMARY KEY,
name text NOT NULL,
begin_date text,
end_date text
);'''
conn.execute(query_create)
query_insert = '''insert into projects (id, name, begin_date, end_date) values (1,"name","date","date")'''
conn.execute(query_insert)
query_select = '''select * from projects'''
cur = conn.execute(query_select)
print(cur.fetchall())
def delete(table: str, name: str):
query = f"DELETE FROM {table} WHERE name = ?"
print(query)
conn.execute(query, (name,))
delete('projects', 'name')
cur = conn.execute(query_select)
print(cur.fetchall())
Gives Output:
[(1, 'name', 'date', 'date')]
DELETE FROM projects WHERE name = ?
[]

is there a way to fix this error i am getting?

This is the frontend of my program. This a function to delete a set of records from a table. It gives me this error:project1Database.deleteRec(sd[0])
NameError: name 'sd' is not defined. I know it probably a little mistake by I am still new to coding so anything can help.
def EmployeeRec(event):
global sd
searchEmp = employeelist.curselection()[0]
sd = employeelist.get(searchEmp)
self.txtEmpID.delete(0,END)
self.txtEmpID.insert(0,sd[1])
self.txtFirstname.delete(0,END)
self.txtFirstname.insert(END,sd[2])
self.txtMiddlename.delete(0,END)
self.txtMiddlename.insert(END,sd[3])
self.txtLastname.delete(0,END)
self.txtLastname.insert(END,sd[4])
self.txtDob.delete(0,END)
self.txtDob.insert(END,sd[5])
self.txtNationality.delete(0,END)
self.txtNationality.insert(END,sd[6])
self.txtNI.delete(0,END)
self.txtNI.insert(END,sd[7])
self.txtAddres.delete(0,END)
self.txtAddres.insert(END,sd[8])
self.txtPostcode.delete(0,END)
self.txtPostcode.insert(END,sd[9])
self.txtphonenumber.delete(0,END)
self.txtphonenumber.insert(END,sd[10])
self.txtEmail.delete(0,END)
self.txtEmail.insert(END,sd[11])
self.txtPassportnumber.delete(0,END)
self.txtPassportnumber.insert(END,sd[12])
self.txtPassportexpirydate.delete(0,END)
self.txtPassportexpirydate.insert(END,sd[13])
self.txtgender.delete(0,END)
self.txtgender.insert(END,sd[14])
def deleteData():
if(len(EmpID.get())!=0):
project1Database.deleteRec(sd[0])
clearData()
displayData()
This is the backend. This is the table for my program.
import sqlite3
#backend
def employeeData():
conn = sqlite3.connect('projectv4.db')
c= conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS employee(EmployeeID INTEGER PRIMARY KEY,EmpID text,
Firstname text,Middlename text, Lastname text,
Dob text, Nationality text, NI text, Addres text, Postcode text, phonenumber text,
Email text, Passportnumber text, Passportexpirydate text,
gender text)""")
conn.commit()
conn.close()
This is the function I am trying to call from my frontend:
def deleteRec(EmployeeID):
conn = sqlite3.connect('projectv4.db')
c= conn.cursor()
c.execute("DELETE FROM employee WHERE EmployeeID = ?", (EmployeeID,))
conn.commit()
conn.close()
deleteData refers to sd before initializing it. Assuming you mean the same global variable as in EmployeeRec, you need to explicitly state that it's global:
def deleteData():
if(len(EmpID.get())!=0):
global sd #here!
project1Database.deleteRec(sd[0])
clearData()
displayData()

Taking value from column in one sqlite3 table and inserting into another

I am trying to add a feature to my program where a teacher sets homework to users from a class they've made. There is a table for users where each user has a unique UserID, classname, firstname and surname. I am trying to take the userIDs of students who are in a certain class, and insert them into a HomeworkSet table. I am able to retrieve the userIDs successfully, but when I insert them into the HomeworkSet table, the values appear as (for example) ('2a1910e919a84230bfc2a7111160cade',), and I am not sure how I am meant to remove the brackets and apostraphes.
def Class_sethw():
homeworktoset = Homework_To_Set.get()
#print (homeworktoset)
conn = sqlite3.connect('MyComputerScience.db')
c = conn.cursor()
homeworkID = c.execute("SELECT HWID FROM HomeworkInfo WHERE HomeworkName = ?", (homeworktoset, )).fetchone()
print (homeworkID)
c.execute("SELECT UserID FROM users WHERE ClassName = ?", (ClassName_SetHWR, ))
homeworksetlist = c.fetchall()
print (homeworksetlist)
for i in (homeworksetlist):
#x = i
#firstname, lastname = x.split(" ")
c.execute('insert INTO HomeworkSet (HWID, StudentID)VALUES(?,?);', ((homeworkID[0]), str(i)))
conn.commit()
Label(sethw, text = "Homework Set!", fg = "GREEN").place(relx=0.205, rely=0.445, height=34, width=97)
This is the code I have used.
You should change this line:
for i in (homeworksetlist):
to:
for i in homeworksetlist:

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

Sqlite 3 multiple foreign keys

I'm working on my A2 coursework and I've run into a problem with multiple foreign keys. Here is all code I think is relevant, if you need more please reply saying so.
In TeacherInfo:
def TMenu():
print()
MenuPupil = menuClass.Menu("Teacher")
MenuPupil.printMenu()
Choice = int(input("Enter your choice: "))
if Choice == 1:
db_name = "PupilPremiumTableNew.db"
sql= """Create table TeacherInfo
(TeacherID int,
TeacherInitials text,
TeacherYearTeaching int,
primary key(TeacherID))"""
CreateTeachersTable(db_name, "TeacherInfo",sql)
In PupilPremiumTableNew:
db_name = "PupilPremiumTableNew.db"
sql= """Create table PupilPremiumTableNew
(PupilID int,
WritingGrade text,
ReadingGrade text,
MathsGrade text,
Term text,
RecordID int,
InterventionsReading text,
InterventionsWriting text,
InterventionsMaths text,
primary key(RecordID),
foreign key(PupilID)
references PupilInfo(PupilID)
foreign key(TeacherID)
references TeacherInfo (TeacherID)
on update cascade on delete cascade)"""
CreatePupilPremiumTable(db_name, "PupilPremiumTableNew",sql)
def CreateTeachersTable(db_name,table_name,sql):
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("select name from sqlite_master where name =?",(table_name,))
result = cursor.fetchall()
keep_table = True
if len(result) == 1:
response = input("The table {0} already exists, do you wish to recreate it?(y/n): ".format(table_name))
if response == 'y':
keep_table = False
print("The table {0} has been recreated, all existing data has been deleted. ".format(table_name))
cursor.execute("drop table if exists {0}".format(table_name))
db.commit()
else:
print("Existing table was kept. ")
else:
keep_table = False
if not keep_table:
cursor.execute(sql)
db.commit()
The error I get says: sqlite3.OperationalError: unknown column "TeacherID" in foreign key definition
As you may notice a foreign key from another file, PupilTable is in there. At the moment that one works, if I remove TeacherID as a foreign key it all works
Thanks
Devilb77
I forgot to tell it what TeacherID was, so to fix the issue I added TeacherID int, into the variable sql
Here is what it now looks like:
db_name = "PupilPremiumTableNew.db"
sql= """Create table PupilPremiumTableNew
(PupilID int,
WritingGrade text,
ReadingGrade text,
MathsGrade text,
Term text,
RecordID int,
InterventionsReading text,
InterventionsWriting text,
InterventionsMaths text,
TeacherID int,
primary key(RecordID),
foreign key(PupilID)
references PupilInfo(PupilID)
foreign key(TeacherID)
references TeacherInfo (TeacherID)
on update cascade on delete cascade)"""
CreatePupilPremiumTable(db_name, "PupilPremiumTableNew",sql)

Categories

Resources