Python SQLite3 Trying to decrement a value - python

First, I'm sorry if this is an absolute mess - this is my first time messing with sqlite3, and I'm still very amateur in python. Anyway, I'm making a D&D encounter tracker and thus far I can add, edit, and remove players/creatures from their own databases. Below is the button click function for when you click "Damage Target" I've successfully made the dropdowns work and added the box for entry of the damage taken, but I've hit a wall and I'm not sure what I need to do.
The error I am receiving is: NameError: name 'hp' is not defined. I had thought I defined that within the table, and the c.execute("""UPDATE players SET...) command would directly reference the hp of the target. How can I get this to function?
def damageButtonClick():
top = Toplevel()
top.title("Damage Target")
def submitPlayerDB():
conn = sqlite3.connect("players.db")
c = conn.cursor()
use = playerOIDList[playerList.index(var2.get())]
c.execute("""UPDATE players SET
hp = :hp,
WHERE oid = :oid""", {
'hp': hp()-damageBox,
'oid': use
})
#log damage amount to present encounter/round to the specific player
conn.commit()
conn.close()
update()
destroy()
def submitCreatureDB():
conn = sqlite3.connect("creature.db")
c = conn.cursor()
use = creatureOIDList[creatureList.index(var2.get())]
c.execute("""UPDATE creatures SET
hp = :hp,
WHERE oid = :oid""", {
'hp': hp() - damageBox,
'oid': use
})
# log damage amount to present encounter/round to the specific player
conn.commit()
conn.close()
update()
destroy()
def destroy():
top.destroy()
conn = sqlite3.connect("players.db")
c = conn.cursor()
c.execute("SELECT *, oid FROM players")
players = c.fetchall()
playerList = []
playerOIDList = []
for player in players:
playerList.append(player[0])
playerOIDList.append(player[8])
conn = sqlite3.connect("creatures.db")
c = conn.cursor()
c.execute("SELECT *, oid FROM creatures")
creatures = c.fetchall()
creatureList = []
creatureOIDList = []
for creature in creatures:
creatureList.append(creature[0])
creatureOIDList.append(creature[8])
preselection = ["Player", "Creature"]
selection = ""
def createSubmitPlayer():
submit = Button(top, text="Submit", command = submitPlayerDB())
submit.grid(row=6, column=0, columnspan=2, pady=10, padx=5, ipadx=100)
def createSubmitCreature():
submit = Button(top, text="Submit", command=submitCreatureDB())
submit.grid(row=6, column=0, columnspan=2, pady=10, padx=5, ipadx=100)
def playerDropdown():
var2.set(playerList[0])
dropDown2 = OptionMenu(top, var2, *playerList)
dropDown2.grid(row=1, column=0)
createSubmitPlayer()
def creatureDropdown():
var2.set(creatureList[0])
dropDown2 = OptionMenu(top, var2, *creatureList)
dropDown2.grid(row=1, column=0)
createSubmitCreature()
def Selection(self):
selection = var.get()
if selection == "Player":
playerDropdown()
elif selection == "Creature":
creatureDropdown()
damageLabel = Label(top, text="Insert Damage Number: ")
damageLabel.grid(row=5, column=0)
damageBox = Entry(top)
damageBox.grid(row=5, column = 1)
cancel = Button(top, text="Cancel", command=top.destroy)
cancel.grid(row=6, column=1, columnspan=2, pady=10, padx=5, ipadx=100)
var = StringVar()
var2 = StringVar()
var.set("Make a Selection")
dropDown1 = OptionMenu(top, var, "Player", "Creature", command = Selection)
dropDown1.grid(row=0, column=0)
conn.commit()
conn.close()
update()

python complains about this 'hp': hp()-damageBox, because there is not a function named hp.
To subtract from a column, sql syntax, that would be something like:
UPDATE player
set hp = hp - someNumber
WHERE .....
sqlite already has hp of the player, so the parameter to substitue would be damageBox giving python syntax like:
c.execute("""UPDATE players SET
hp = hp - :damageBox,
WHERE oid = :oid""", {
'damageBox': damageBox,
'oid': use
})

Related

How to delete a specific occurrence with a delete button?

I have an iteration in my code which show for each line : ID / Name / Button Delete. You can see the image below. I would like when i click on one of the delete button that the data on the same line be deleted.
I try my best, you can see my code. How i can do it ?
Thank you a lot.
from tkinter import *
import mysql.connector
def main():
root = Tk()
conn = mysql.connector.connect(user='root', password='', host='localhost',
database='showmanager')
my_cursor = conn.cursor()
var_i = 3
def del_customer():
my_cursor.execute("DELETE FROM `spectator` "
"WHERE `spectator`.`id_customer` = "+user[0]+"")
my_cursor.execute("SELECT * FROM spectator")
users = my_cursor.fetchall()
for user in users:
label = Label(root, text=user, font=9)
label.grid(row=int(var_i), column=1)
Button(root, text="Delete spectator", font=9, height=1,
command=del_customer).grid(row=int(var_i), column=4)
var_i = var_i + 1
root.mainloop()
if __name__ == '__main__':
main()
You can pass the customer ID and corresponding widgets (label and button) to del_customer() so that you can remove the record in the database based on the customer ID and the corresponding label and button inside the function:
def del_customer(cust_id, widgets):
my_cursor.execute("DELETE FROM spectator WHERE id_customer = %s", [cust_id])
conn.commit() # make the change effective
# remove the corresponding label and button
for w in widgets:
w.destroy()
...
for user in users:
label = Label(root, text=user)
label.grid(row=var_i, column=1)
btn = Button(root, text="Delete spectator")
btn.grid(row=var_i, column=4)
var_i += 1
# pass the customer ID, label and button to del_customer()
btn['command'] = lambda cust_id=user[0], widgets=(label, btn): del_customer(cust_id, widgets)

Please help me with the global variable

So here's my code, I've been following the tutorial from this guy https://www.youtube.com/watch?v=YXPyB4XeYLA&t=13094s
#4:35:30
The part where I stuck on is when he talked about using global variable.
Whenever I press update record, it shows me error message
line 80, in update
'first': f_name_editor.get(),
NameError: name 'f_name_editor' is not defined
So I went back to check the global variable, it says:
Global variable 'f_name_editor' is undefined at the module level
I am out of ideas already and I still cannot figure it out. I followed all the steps and went back and forth to see if I missed anything during the video and I still can't find the problem
Please help me!
from tkinter import *
import sqlite3
root = Tk()
root.title('Family Member List')
root.geometry('400x400')
conn = sqlite3.connect('Family_list.db')
c = conn.cursor()
'''
c.execute("""CREATE TABLE family(
first_name text,
last_name text,
gender text,
occupation text
)
#""")
'''
#Edit function to update record
def edit():
editor = Tk()
editor.title('Update Record')
editor.geometry('400x400')
conn = sqlite3.connect('Family_list.db')
c = conn.cursor()
record_id = delete_box.get()
c.execute("SELECT * FROM family WHERE oid =" + record_id)
records = c.fetchall()
global f_name_editor
f_name_editor = Entry(editor,width=30)
f_name_editor.grid(row=0, column=1, padx=20)
l_name_editor = Entry(editor,width=30)
l_name_editor.grid(row=1, column=1, padx=20)
gender_editor = Entry(editor,width=30)
gender_editor.grid(row=2, column=1, padx=20)
occupation_editor = Entry(editor,width=30)
occupation_editor.grid(row=3, column=1, padx=20)
f_name_label = Label(editor,text= 'First Name')
f_name_label.grid(row=0, column =0)
l_name_label = Label(editor,text= 'Last Name')
l_name_label.grid(row=1, column =0)
gender_label = Label(editor,text= 'Gender')
gender_label.grid(row=2, column =0)
occupation_label = Label(editor,text= 'Occupation')
occupation_label.grid(row=3, column =0)
# LOOP THROUGH RESULT
for record in records:
f_name_editor.insert(0, record[0])
l_name_editor.insert(0, record[1])
gender_editor.insert(0, record[2])
occupation_editor.insert(0, record[3])
#Save Button after edited
edit_btn = Button(editor, text='Save Record', command = update)
edit_btn.grid(row=6, column = 1, columnspan = 2, pady=10, padx = 10, ipadx= 100)
def update():
conn = sqlite3.connect('Family_list.db')
c = conn.cursor()
record_id = delete_box.get()
c.execute('''UPDATE family SET
first_name=:first,
last_name=:last,
gender=:gender,
occupation=:occupation
WHERE oid = :oid''',
{
'first': f_name_editor.get(),
'last': l_name_editor.get(),
'gender': gender_editor.get(),
'occupation': occupation_editor.get(),
'oid': record_id
})
conn.commit()
conn.close()
def delete():
conn = sqlite3.connect('Family_list.db')
c = conn.cursor()
c.execute("DELETE from family WHERE oid=" + delete_box.get())
conn.commit()
conn.close()
def submit():
conn = sqlite3.connect('Family_list.db')
c = conn.cursor()
c.execute("INSERT INTO family VALUES (:f_name,:l_name,:gender,:occupation)",
{
'f_name':f_name.get(),
'l_name':l_name.get(),
'gender': gender.get(),
'occupation': occupation.get(),
})
conn.commit()
conn.close()
f_name.delete(0,END)
l_name.delete(0,END)
gender.delete(0,END)
occupation.delete(0,END)
def query():
conn = sqlite3.connect('Family_list.db')
c = conn.cursor()
c.execute('SELECT *, oid FROM family')
records = c.fetchall()
print(records)
conn.commit()
conn.close()
print_records = ''
for record in records:
print_records += str(record[0]) + " \t "+ str(record[4]) +'\n'
query_label = Label(root,text= print_records)
query_label.grid(row = 8 ,column = 0, columnspan =2 )
f_name = Entry(root,width=30)
f_name.grid(row=0, column=1, padx=20)
l_name = Entry(root,width=30)
l_name.grid(row=1, column=1, padx=20)
gender = Entry(root,width=30)
gender.grid(row=2, column=1, padx=20)
occupation = Entry(root,width=30)
occupation.grid(row=3, column=1, padx=20)
delete_box= Entry(root, width=30)
delete_box.grid(row=9, column = 1)
#create global variable
f_name_label = Label(root,text= 'First Name')
f_name_label.grid(row=0, column =0)
l_name_label = Label(root,text= 'Last Name')
l_name_label.grid(row=1, column =0)
gender_label = Label(root,text= 'Gender')
gender_label.grid(row=2, column =0)
occupation_label = Label(root,text= 'Occupation')
occupation_label.grid(row=3, column =0)
delete_box_label = Label(root, text = 'Select ID Number')
delete_box_label.grid(row=9, column= 0)
#BUTTONS
submit_btn = Button(root,text='Add Record to Database', command= submit)
submit_btn.grid(row = 4, column =0, columnspan=2, pady=10, padx =10, ipadx=100)
query_btn = Button(root, text='Check Submission', command = query)
query_btn.grid(row=5, column = 0, columnspan = 2, pady=10, padx = 10, ipadx= 100)
delete_btn = Button(root, text='Delete Record', command = delete)
delete_btn.grid(row=10, column = 0, columnspan = 2, pady=10, padx = 10, ipadx= 100)
#Update Button
edit_btn = Button(root, text='Update Record', command = update)
edit_btn.grid(row=11, column = 0, columnspan = 2, pady=10, padx = 10, ipadx= 100)
conn.commit()
conn.close()
root.mainloop()
f_name_editor does not exist in global scope until the edit function creates it. The codepath that calls the update function does not pass through the edit function, so the global variable does not exist at that point. You could declare it in global scope, but you'll likely find that just leads to more bugs.

"if" statement used to display an error tkinter.messagebox is not working

I'm trying to create a function in where if the values I enter is null a ttk.messagebox will appear to inform the user that the correct values must be entered. When I enter null values for prce or uprce, it only gives me error messages instead of the messagebox displaying. I've tried using a button to make the same messagebox show and it works but now that I try to use an "if" statement for it, it does not show up
Here is my sample code
import tkinter
from tkinter import*
from tkinter import ttk, LabelFrame
import tkinter.messagebox
import sqlite3
conn = sqlite3.connect('newtest.db')
c = conn.cursor()
top = tkinter.Tk()
def update(show):
trv.delete(*trv.get_children())
for i in show:
trv.insert("", 'end', values=i)
return show
def submitprod():
database_insert()
current_db_data = query_database()
update(current_db_data)
# reset
pdesc.delete(0, END)
qty.delete(0, END)
prce.delete(0, END)
uprce.delete(0, END)
conn.commit()
def query_database():
query = "SELECT oid, pdesc, qty, prce, uprce, markup from products"
conn = sqlite3.connect('newtest.db')
c = conn.cursor()
c.execute(query)
show = c.fetchall()
return show
def error():
tkinter.messagebox.showinfo("Error! Enter Value!")
def database_insert():
conn = sqlite3.connect('newtest.db')
c = conn.cursor()
if prce.get == None:
error()
if uprce.get == None:
error()
pprce1 = int(prce.get())
uprce1 = int(uprce.get())
mup = (pprce1 - uprce1 / uprce1 * 100)
print(mup)
c.execute("INSERT INTO products VALUES (:pdesc, :qty, :prce, :uprce, :mup1)",{
'pdesc': pdesc.get(),
'qty': qty.get(),
'prce': prce.get(),
'uprce': uprce.get(),
'mup1': mup})
conn.commit()
box2 = LabelFrame(top)
box2.pack (fill="both", expand="yes", padx=20, pady=10)
box1 = LabelFrame(top, text="Entry")
box1.pack (fill="both", expand="yes", padx=20, pady=10)
pdesc = Entry(box1, width=30)
pdesc.grid(row=1, column=1, padx=20)
qty = Entry(box1, width=30)
qty.grid(row=2, column=1, padx=20)
prce = Entry(box1, width=30)
prce.grid(row=3, column=1, padx=20)
uprce = Entry(box1, width=30)
uprce.grid(row=4, column=1, padx=20)
pdesc_label = Label(box1, text='Product')
pdesc_label.grid(row=1, column=2)
qty_label = Label(box1, text='Quantity')
qty_label.grid(row=2, column=2)
prce_label = Label(box1, text='Price')
prce_label.grid(row=3, column=2)
uprce_label = Label(box1, text='Unit Price')
uprce_label.grid(row=4, column=2)
trv = ttk.Treeview(box2, column=(1,2,3,4,5,6), show="headings", height="20")
style=ttk.Style(trv)
style.configure('Treeview', rowheight=20)
trv.pack(side=LEFT)
trv.heading(1, text="Product ID")
trv.heading(2, text="Product Description")
trv.heading(3, text="Quantity")
trv.heading(4, text="Price")
trv.heading(5, text="Unit Price")
trv.heading(6, text="Return Percentage")
#data for products//show1
conn = sqlite3.connect('new1.db')
query = "SELECT oid, pdesc, qty, prce, uprce, markup from products"
c.execute(query)
show = c.fetchall()
update(show)
#submit product button
btn2 = ttk.Button(box1, text='Enter', command=submitprod)
btn2.grid(row=6, column=1, columnspan=1, pady=10, padx=10, ipadx=10)
top.title("error test")
top.geometry("1500x1200")
top.mainloop()
and here is the error message I get
line 22, in submitprod
database_insert()
line 54, in database_insert
pprce1 = int(prce.get())
ValueError: invalid literal for int() with base 10: ''
You have several errors. 1) you need to add the () to the end of the get() method 2) you need to compare to an empty string "", not None 3) you need to add a return to stop the function if an error occurs and 4) you need to provide a title for your error popup.
if prce.get() == "":
error()
return
That said it would be more pythonic to use a try block instead of an if block, like this:
def error():
tkinter.messagebox.showinfo("Error", "Invalid Value!")
def database_insert():
try:
pprce1 = int(prce.get())
uprce1 = int(uprce.get())
except ValueError:
error()
return # stop this function
mup = (pprce1 - uprce1 / uprce1 * 100)
print(mup)
conn = sqlite3.connect('newtest.db')
c = conn.cursor()
c.execute("INSERT INTO products VALUES (:pdesc, :qty, :prce, :uprce, :mup1)",{
'pdesc': pdesc.get(),
'qty': qty.get(),
'prce': prce.get(),
'uprce': uprce.get(),
'mup1': mup})
conn.commit()
That would also catch if the user types "banana" or something.

Python / Tkinter - Error message when I try to save changes

I am building a database for tools and matrials list in Python using Tkinter for the GUI. I am running into issues when I try to edit data. Everything works until I click the save button in the editor window. It says: sqlite3.ProgrammingError: You did not supply a value for binding 1. Can anyone see what I am doing wrong here?
Here is my code:
from tkinter import *
import sqlite3
mud = Tk()
mud.title("Mud Data")
mud.geometry("400x600")
# Create database
conn = sqlite3.connect('well_sav.db')
# Create cursor
c = conn.cursor()
# Create table
# c.execute("""CREATE TABLE mud (
# mud_type text,
# mud_weight real ,
# mud_viscosity real,
# mud_pit_number real
# )""")
# Create Submit Function for DB
def submit():
# Connect to DB
conn = sqlite3.connect('well_sav.db')
# Create cursor
c = conn.cursor()
# Insert into table
c.execute("INSERT INTO mud VALUES (:mud_type, :mud_weight, :mud_viscosity, :mud_pit_number)",
{
'mud_type': mud_type.get(),
'mud_weight': mud_weight.get(),
'mud_viscosity': mud_viscosity.get(),
'mud_pit_number': mud_pit_number.get()
})
# Commit changes
conn.commit()
# Close connection
conn.close()
# Clear The Text Boxes
mud_type.delete(0, END)
mud_weight.delete(0, END)
mud_viscosity.delete(0, END)
mud_pit_number.delete(0, END)
# Function to edit a record
def edit():
# Create global variables
global editor
global mud_type_editor
global mud_weight_editor
global mud_viscosity_editor
global mud_pit_number_editor
editor = Tk()
editor.title("Edit mud")
editor.geometry("400x200")
conn = sqlite3.connect('well_sav.db')
c = conn.cursor()
record_id = delete_box.get()
c.execute("SELECT * FROM mud WHERE oid = " + record_id)
records = c.fetchall()
mud_type_editor = Entry(editor, width=30)
mud_type_editor.grid(row=0, column=1, pady=(10, 0))
mud_weight_editor = Entry(editor, width=30)
mud_weight_editor.grid(row=1, column=1)
mud_viscosity_editor = Entry(editor, width=30)
mud_viscosity_editor.grid(row=2, column=1)
mud_pit_number_editor = Entry(editor, width=30)
mud_pit_number_editor.grid(row=3, column=1)
# Create Text box Label
mud_type_label = Label(editor, text="Mud Type")
mud_type_label.grid(row=0, column=0, pady=(10, 0))
mud_weight_label = Label(editor, text="Mud Weight")
mud_weight_label.grid(row=1, column=0)
mud_viscosity_label = Label(editor, text="Mud Viscosity")
mud_viscosity_label.grid(row=2, column=0)
mud_pit_number_label = Label(editor, text="Mud Pit Number")
mud_pit_number_label.grid(row=3, column=0)
# Loop through results
for record in records:
mud_type_editor.insert(0, record[0])
mud_weight_editor.insert(0, record[1])
mud_viscosity_editor.insert(0, record[2])
mud_pit_number_editor.insert(0, record[3])
# Create save button
edit_button = Button(editor, text="Save Update", command=update)
edit_button.grid(row=7, column=1, pady=5, padx=5, ipadx=98)
conn.commit()
conn.close()
# Fucntion for updates
def update():
conn = sqlite3.connect('well_sav.db')
c = conn.cursor()
record_id = delete_box.get()
c.execute("""UPDATE mud SET
mud_type = :name,
mud_weight = :length,
mud_viscosity = :inside_diameter,
mud_pit_number = :outside_diameter
WHERE oid = :oid""",
{
'mud_type': mud_type_editor.get(),
'mud_weight': mud_weight_editor.get(),
'mud_viscosity': mud_viscosity_editor.get(),
'mud_pit_number': mud_pit_number_editor.get(),
'oid': record_id
})
conn.commit()
conn.close()
editor.destroy()
# Function to delete a record
def delete():
conn = sqlite3.connect('well_sav.db')
c = conn.cursor()
c.execute("DELETE FROM mud WHERE oid = " + delete_box.get())
conn.commit()
conn.close()
# Create Query Function
def query():
# Connect to DB
conn = sqlite3.connect('well_sav.db')
# Create cursor
c = conn.cursor()
# Query the DB
c.execute("SELECT *, oid FROM mud")
records = c.fetchall()
# print(records)
# Loop through results
print_records = ''
for record in records:
print_records += str(record[0]) + "\t " + str(record[1]) + \
"\t " + str(record[2]) + "\t " + \
str(record[3]) + str(record[4]) + "\n"
query_label = Label(mud, text=print_records)
query_label.grid(row=20, column=0, columnspan=2)
# Commit changes
conn.commit()
# Close connection
conn.close()
# Math Functions
def volume_per_foot(bha_result_text):
bha_gallons_per_foot = float(mud_viscosity.get()) * \
float(mud_viscosity.get()) / 1029.4
bha_result_text.set(str(bha_gallons_per_foot))
# Create Text Boxes
mud_type = Entry(mud, width=30)
mud_type.grid(row=0, column=1, pady=(10, 0))
mud_weight = Entry(mud, width=30)
mud_weight.grid(row=1, column=1)
mud_viscosity = Entry(mud, width=30)
mud_viscosity.grid(row=2, column=1)
mud_pit_number = Entry(mud, width=30)
mud_pit_number.grid(row=3, column=1)
delete_box = Entry(mud, width=30)
delete_box.grid(row=6, column=1)
# Create Text box Label
mud_type_label = Label(mud, text="Mud Type")
mud_type_label.grid(row=0, column=0, pady=(10, 0))
mud_weight_label = Label(mud, text="Mud Weight")
mud_weight_label.grid(row=1, column=0)
mud_viscosity_label = Label(mud, text="Mud Viscosity")
mud_viscosity_label.grid(row=2, column=0)
mud_pit_number_label = Label(mud, text="Pit Number")
mud_pit_number_label.grid(row=3, column=0)
delete_box_label = Label(mud, text="Select ID")
delete_box_label.grid(row=6, column=0)
# Create Submit Button
submit_button = Button(mud, text="Save", command=submit)
submit_button.grid(row=4, column=1, pady=5, padx=5, ipadx=121)
# Create Query Button
query_button = Button(mud, text="Show Muds", command=query)
query_button.grid(row=5, column=1, pady=5, padx=5, ipadx=79)
# Create edit button
edit_button = Button(mud, text="Edit Muds", command=edit)
edit_button.grid(row=7, column=1, pady=5, padx=5, ipadx=87)
# Create delete button
delete_button = Button(mud, text="Delete Mud", command=delete)
delete_button.grid(row=8, column=1, pady=5, padx=5, ipadx=80)
# Commit changes
conn.commit()
# Close connection
conn.close()
mud.mainloop()
And here is the error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
return self.func(*args)
File "mud.py", line 123, in update
c.execute("""UPDATE mud SET
sqlite3.ProgrammingError: You did not supply a value for binding 1.
Hi #LoudEye and welcome to Stack Overflow! Try using ? instead of : like this:
c.execute("UPDATE mud SET mud_type=?,mud_weight = ?, mud_viscosity=?, mud_pit_number = ? WHERE...",(mud_type_editor.get(), mud_weight_editor.get(),mud_viscosity_editor.get(),mud_pit_number_editor.get()))
Note: You should also use WHERE also with question mark like I've used with SET

How do I fix 'MySQLConverter' object has no attribute '_entry_to_mysql' for inventory input, python-mysql?

I am pretty new to Python, but for a team design project I need to create a code to input information into a Tkinter window that is connected to a mysql table and update that table accordingly. If the same ID is inputted again it should update the quantity +1 :
from Tkinter import*
import tkMessageBox
import tkFont
import mysql.connector
import time
def AddItem():
print "Added Item"
print "ID:" + ID.get()
print "Item Name:" + ItemName.get()
print "Price Per Item:" + PricePerItem.get()
print "Manufacturer:" + Manufacturer.get()
The s = INSERT INTO inventory... is throwing me for a loop, I can input the information into the Tkinter window but when I select the Add Item button, this error shows up:
ProgrammingError: Failed processing format-parameters; 'MySQLConverter' object has no attribute '_entry_to_mysql'
cnx = mysql.connector.connect(user='root',password='cj92cj',
database='INVENTORY', use_unicode=False)
s = "INSERT INTO inventory (ID, Manufacturer, ItemName, PricePerItem, Quantity) VALUES({},{},{},{},1) ON DUPLICATE KEY UPDATE Quantity= Quantity + 1, Manufacturer = VALUES(Manufacturer), ItemName = VALUES(ItemName), PricePerItem = VALUES(PricePerItem);".format(ID.get(),Manufacturer.get(),ItemName.get(),PricePerItem.get())
print ID.get()
print s
cursor = cnx.cursor()
cursor.execute(s, (ID, Manufacturer, ItemName, PricePerItem, Quantity))
cursor.close()
cnx.commit()
cnx.close()
def ClearEntries():
ItemName.delete(0,END)
PricePerItem.delete(0,END)
Manufacturer.delete(0,END)
I have been trying all sorts of things with "s" for hours and hours but I am having trouble figuring out the right syntax to use.
Below is the Tkinter Window code if that helps at all.
def InformationInput():
BigFont=tkFont.Font(family="Arial", size=14, weight="bold")
root.title("Enter Item Information")
root.geometry("1000x400")
root.bind("<Return>", lambda event: AddItem())
lbl1 = Label(root, text="ID:")
lbl2 = Label(root, text="Item Name:")
lbl3 = Label(root, text="Price Per Item:")
lbl4 = Label(root, text="Manufacturer:")
lbl9 = Label(root, text="Enter Item Information", height=3, fg="red", font=BigFont)
global ID, ItemName, PricePerItem, Manufacturer
ID = Entry(root, width=25, textvariable=ID)
ItemName = Entry(root, width=20, textvariable=ItemName)
PricePerItem = Entry(root, width=10, textvariable=PricePerItem)
Manufacturer = Entry(root, width=25, textvariable=Manufacturer)
button1 = Button(root, text="Add Item", command=AddItem, width=15)
button2 = Button(root, text="Clear Entries", command=ClearEntries, width=15)
button3 = Button(root, text="Exit", command=root.destroy, width=15)
lbl9.grid(column=2, row=1, columnspan=5)
lbl1.grid(column = 1, row = 4, sticky="nw")
ID.grid(column = 2, row = 4, sticky="nw")
lbl2.grid(column = 3, row = 4)
ItemName.grid(column = 4, row = 4)
lbl3.grid(column = 5, row = 4)
PricePerItem.grid(column = 6, row = 4, sticky="w")
lbl4.grid(column = 3, row = 10)
Manufacturer.grid(column = 4, row = 10)
button1.grid(column=3, row=15, sticky="e", pady=20)
button2.grid(column=4, row=15)
button3.grid(column=5, row=15, sticky="w")
root = Tk()
ID = IntVar()
ItemName = StringVar()
PricePerItem = IntVar()
Manufacturer = StringVar()
Quantity = IntVar()
InformationInput()
root.mainloop()
You have to use parameter marks in your query or your database driver, in this case MySQL Connector/Python, will through an error. Also, you have to pass values which can be converted. MySQLConverter does not know how to convert entry-objects, so it tells you it can't convert it (although it can be a bit more explicit).
Here is an example (simplified):
s = ("INSERT INTO inventory (ID, Manufacturer, ItemName, PricePerItem, Quantity) "
"VALUES (%s, %s, %s, %s, %s) ON DUP..")
cursor = cnx.cursor()
cursor.execute(s, (ID.get(), Manufacturer.get(), ItemName.get(),
PricePerItem.get(), Quantity.get()))
I took the liberty opening a bug report to improve the error message.
Other remark: I don't think you need to give the ID when inserting? Usually that is an AUTO_INCREMENT.

Categories

Resources