sqlite3.OperationalError: near "": syntax error - python

i keep getting this error when i try to add a column and give it a name
sqlite3.OperationalError: near "100": syntax error
here is my code (minimal)
from tkinter import *
import sqlite3
from tkinter import messagebox
conr = sqlite3.connect("CE.db")
curr = conr.cursor()
rt = Tk()
def add():
ID = e30.get()
curr.execute('alter table cust add {}'.format(ID))
lbl30 = Label(rt, text= "Your ID")
lbl30.grid (row = 0, column = 0)
e30 = Entry(rt, width = 30)
e30.grid(row = 0, column = 1)
buttt1 = Button(rt, text = 'Submit', command = add, width = 20)
buttt1.grid(row = 1, column = 0, columnspan = 2)
rt.mainloop()
can someone please tell me what i am doing wrong and how i can fix it.

The line
curr.execute('alter table cust add {}'.format(ID))
is being formatted and executed as
alter table cust add 100
This is not valid SQLite syntax
The correct syntax can be found at:
SQlite Alter Syntax

Related

My search in python using tree view is not working/displaying the search results

This is my two functions which operate my search. The problem seems to occur with my search function when I binded it to my key releases on my search entries. However when I search with my button it works with no error messages .
def SearchCustomer(self):
connection = sqlite3.connect("Guestrecord.db")
cursor = connection.cursor()
columnID = ["title","firstName","surname","dob","payment","email","address","postcode"]
columnStr =["Title","FirstName","Surname","DOB","Payment","Email","Address","Postcode"]
self.search_table = ttk.Treeview(self.search_frame,columns=columnID,show="headings")
self.search_table.bind("<Motion>","break")
for i in range(0,8):
self.search_table.heading(columnID[i],text = columnStr[i])
self.search_table.column(columnID[i],minwidth = 0, width = 108)
self.search_table.place(x=20,y=0)
for GuestRec in cursor.execute("SELECT * FROM tb1Guest1"):
self.search_table.insert("",END,values=GuestRec)
connection.commit()
connection.close()
SearchCustomer(self)
search_icon = Image.open("search icon.png")
search_icon_resize = search_icon.resize((20,20))
search_icon = search_icon_resize
search_icon_photo = ImageTk.PhotoImage(search_icon)
self.search_firstname = Entry(self.search_frame2, width=30,bg="#e2f0d9",font=("Avenir Next",18),highlightthickness = 0,relief=FLAT)
self.search_firstname.place(x = 140, y =0)
self.search_firstname_label = Label(self.search_frame2,bg = "white", text = "First Name", font=("Avenir Next",20))
self.search_firstname_label.place(x= 20,y=0)
self.search_Surname = Entry(self.search_frame2, width=30,bg="#e2f0d9",font=("Avenir Next",18),highlightthickness = 0,relief=FLAT)
self.search_Surname.place(x = 140, y =40)
self.search_Surname_label = Label(self.search_frame2,bg = "white", text = "Surname", font=("Avenir Next",20))
self.search_Surname_label.place(x= 20,y=40)
searchButton = Button(self.search_frame2, image=search_icon_photo,height = 35, width =35, command=self.Search,bg ="white")
searchButton.place(x= 500, y = 0)
## Binding entries
self.search_firstname.bind("<KeyRelease>",self.Search)
self.search_Surname.bind("<KeyRelease>",self.Search)
def Search(self):
sFirst_Name = self.search_firstname.get()
sSurname = self.search_Surname.get()
search_rec = (sFirst_Name,sSurname)
search_rec_new = tuple(item for item in search_rec if item !="")
search_fields = ["guestFirstname","guestFirstname"]
search_SQL = "SELECT * FROM tb1Guest1 WHERE guestID LIKE '%'"
for i in range(len(search_rec)):
if search_rec[i] != "":
search_SQL += " AND " + search_fields[i] + " LIKE '%' || ? || '%'"
connection = sqlite3.connect("Guestrecord.db")
cursor = connection.cursor()
# Clearing search results
for rec in self.search_table.get_children():
self.search_table.delete(rec)
#Display the records
for GuestRec in cursor.execute(search_SQL,search_rec_new):
self.search_table.insert("",END,values=GuestRec)
connection.commit()
connection.close()
Then this is the message which pops up when I try to type in my search entries:
It may have something to do with my .self but I don't know how I would over come this error
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/tkinter/__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
TypeError: Main_menu.Search() takes 1 positional argument but 2 were given
If someone could provide a solution to my problem it would be great as I have spend seemingly a lot of time trying to figure this error out.
The function for a binding event expects an argument: the Event object. However you also use the same function for a button command which does not expect that extra argument.
So you need to add an optional argument to Search():
# event argument is optional, if not provided, it will be None
def Search(self, event=None):
...

I'm trying to implement a delete button to sqlite3 using pysimplegui

#pysimplegui box where the data will be updated
[sg.Listbox('', size= (50, 10), key='-BOX-')]
#delete function communicating to the database
def deleta_bd(x):
back.dbase = sqlite3.connect('login.db')
c = back.dbase.cursor()
sql_query = """DELETE from login where id = (?)"""
id = x
c.execute(sql_query,(id,))
back.dbase.commit()
#function call
if event == 'Excluir':
if id:
x = values['-BOX-'][0]
deleta_bd(x)
id = visualiza_bd()
window.find_element('-BOX-').update(id)
#error type
c.execute(sql_query,(id,))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type

Refresh labels when adding a new item

I'm trying to make a products' management app with tkinter and sqlite 3.
I want to show the products in labels. It works correctly, but I also want to delete every label when I add an item, and then recreate new labels. This way, the list updates when adding a new item.
Otherwise the user needs to restart the app to see the new item. Here's the code:
from tkinter import *
import sqlite3
# table name = items
conn = sqlite3.connect("productManagement.db")
cursor = conn.cursor()
itemsSearch = cursor.execute("SELECT rowid, * FROM items")
itemsFetch = itemsSearch.fetchall()
window = Tk()
window.geometry("800x600")
window.config(bg="#9BB7D4")
#FUNCTIONS
itemFrame = Frame(bg="#8a8a8a",width=200,height=200)
frameTitle = Label(itemFrame,text="Products:",bg="#8a8a8a",font=("Arial Black",12))
frameTitle.pack()
def createProduct():
global itemsFetch
name = nameEntry.get()
price = priceEntry.get()
quantity = quantityEntry.get()
number = numberEntry.get()
cursor.execute(f"INSERT INTO items VALUES ('{name}',{int(price)},{int(quantity)},
{int(number)})")
conn.commit()
itemsSearch = cursor.execute("SELECT rowid, * FROM items")
itemsFetch = itemsSearch.fetchall()
#the problem is here: i create new label for every item but the old ones doesn't
dissapear, i want to delete all the labels of the items existing and create new ones
showProducts()
def showProducts():
global itemStats
for item in itemsFetch:
itemStats = Label(itemFrame,bg="#8a8a8a",font=("Italic",12),
text=f"Name: {item[1]} Price: {int(item[2])}€ Quantity: {int(item[3])}
Item no: {int(item[4])}")
deleteBtn = Button(itemFrame,text="Delete")
itemStats.pack()
showProducts()
#GUI
title = Label(text="Product Managment System",font=("Arial Black",24),bg="#9BB7D4")
nameText = Label(text="Name:",bg="#9BB7D4",font=("Italic",12))
nameEntry = Entry(font=("Italic",12))
priceText = Label(text="Price:",bg="#9BB7D4",font=("Italic",12))
priceEntry = Entry(font=("Italic",12))
quantityText = Label(text="Quantity:",bg="#9BB7D4",font=("Italic",12))
quantityEntry = Entry(font=("Italic",12))
numberText = Label(text="Product Number:",bg="#9BB7D4",font=("Italic",12))
numberEntry = Entry(font=("Italic",12))
createProductBtn = Button(text="Create item",command=createProduct)
#PACKS
title.pack(pady=20)
nameText.place(x=140,y=140)
nameEntry.place(x=190,y=140)
priceText.place(x=340,y=140)
priceEntry.place(x=387,y=140)
quantityText.place(x=125,y=200)
quantityEntry.place(x=190,y=200)
numberText.place(x=340,y=200)
numberEntry.place(x=463,y=200)
createProductBtn.place(x=190,y=260)
itemFrame.place(x=190,y=300)
conn.commit()
window.mainloop()
conn.close()

_tkinter.TclError: wrong # args: should be ".!entry4 insert index text"

I'm trying to list all the data i got from my database using tkinter.
I'm following this post: https://www.geeksforgeeks.org/create-table-using-tkinter/
I got this erorr:
File "/Users/nobu/WorkSpace/Python/CommandLineApps/guineapig/guineapig/gui_tkinter.py", line 18, in __init__
self.entry.insert(END, result[i][j])
File "/usr/local/Cellar/python#3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 3056, in insert
self.tk.call(self._w, 'insert', index, string)
_tkinter.TclError: wrong # args: should be ".!entry4 insert index text"
Here's my code:
from tkinter import *
import mysql.connector
import utils
class Table:
def __init__(self,root, result):
# code for creating table
total_rows = len(result)
total_columns = len(result[0])
for i in range(total_rows):
for j in range(total_columns):
self.e = Entry(root, width=20, fg='white')
self.e.grid(row=i, column=j)
self.e.insert(END, result[i][j]) # <- Here I got an error
def get_all():
connection, cursor = utils.connect_db()
with connection:
root = Tk()
cursor.execute("SELECT * FROM item ORDER BY item_id DESC")
result = cursor.fetchall()
if len(result) == 0:
label = Label(text="There are no items. Please create one.")
else:
table = Table(root, result)
root.mainloop()
I'm very new to tkinter. Please help me solve this issue.
Thank you #Bryan Oakley!
My list has None, so I did this:
if result[i][j] is not None:
self.entry.insert(END, result[i][j])
else:
self.entry.insert(END, "None")

can't get my database to connect to my maths game

Basically I am trying to get my database to connect to my GUI and display a random question, however it is simply not working, any idea?      
SQL = 'SELECT * FROM tblQuestion'
cursor = Databaseconnector.SELECT(SQL)
rows = cursor.fetchall()
rows = random.choice(rows)
print rows.Question, rows.Hint, rows.A1, rows.A2, rows.A3, rows.A4, rows.CorrectAnswer
#def create_widgets(self):
#create welcome label
label1 = Tkinter.Label(self, text = (rows(1).Question))
label1.grid(row = 0, column = 1, columnspan = 2, sticky = 'W')
ERROR: TypeError: ‘pydodbc.Row’ object is not
rows is first a collection of pydodbc.Row objects, but then you alter it to be a single pydodbc.Row object by calling random.choice:
rows = cursor.fetchall() # rows is a list
rows = random.choice(rows) # now rows is a single object
Then you try to call that object using ():
label1 = Tkinter.Label(self, text = (rows(1).Question))
which fails with the error message you provided (partially):
ERROR: TypeError: ‘pydodbc.Row’ object is not callable
The best way to solve this to use a new variable for the single row:
rows = cursor.fetchall()
random_row = random.choice(rows)
...
label1 = Tkinter.Label(self, text = (random_row.Question))

Categories