I'm in a dilemma as to how to give my table name depending on my Combobox selections. I am using PyQt5. I tried it this way but got not the thing right.
b = self.combo.currentText()
sql = '''CREATE TABLE IF NOT EXISTS d (id int, grade text)''')
This creates a database with b as the name instead of the choice from the combobox.
You have to bind the event based on combobox selection using application_cb.bind("<>", createTable) where you have to pass function name
application_label = Label(cbFrameRow1Col2, text='Application', bg='gray46', fg='white', font=("calibri", 10))
application_label.grid(row=0, column=0, sticky='w', padx=10, pady=5)
application_cb = ttk.Combobox(cbFrameRow1Col2, values=application_list, width=15)
application_cb.grid(row=0, column=1, sticky='w', padx=10, pady=5)
application_cb.bind("<<ComboboxSelected>>", createdb)
And now you have to call create table function when this event is triggered
def createTable(event):
tablename = application_cb.get()
conn = sqlite3.connect('temp.db')
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, Name TEXT)" % (tablename))
conn.commit()
conn.close()
Related
I have created a small python tkinter program designed to have a user write data into text entry boxes in the app then insert this data into a MS SQL server database. When clicking the insert button I am getting the following error message, stopping the app from insert the code into SQL.
cursor.execute("INSERT INTO TEST_DISA_MAIN_TABLE VALUES (:DENSITY_VALUE, :DATE, :TIME, :CHART_VALUE)",
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')*
This is my code for the python insert function:
def insertvalue():
# Create a database or connect to one
conn = pyodbc.connect('Driver={SQL Server};'
'Server=MON-SQL-02;'
'Database=ENVIRONMENTAL;'
'Trusted_Connection=yes;')
# Create cursor
cursor = conn.cursor()
# Insert into table
cursor.execute("INSERT INTO TEST_DISA_MAIN_TABLE VALUES (:DENSITY_VALUE, :DATE, :TIME, :CHART_VALUE)",
{
'DENSITY_VALUE': DENSITY_VALUE.get(),
'DATE': DATE.get(),
'TIME': TIME.get(),
'CHART_VALUE': CHART_VALUE.get(),
})
# Commit changes
conn.commit()
#Close Connection
conn.close()
# Clear the text boxes
DENSITY_VALUE.delete(0, END)
DATE.delete(0, END)
TIME.delete(0, END)
CHART_VALUE.delete(0, END)
#Create text boxes
DENSITY_VALUE = Entry(root, width=30)
DENSITY_VALUE.grid(row=2, column=1)
DATE = Entry(root, width=30)
DATE.grid(row=3, column=1)
TIME = Entry(root, width=30)
TIME.grid(row=4, column=1)
CHART_VALUE = Entry(root, width=30)
CHART_VALUE.grid(row=5, column=1)
#Create Text box labels
DENSITY_VALUE_Label = Label(root, text="Density Value")
DENSITY_VALUE_Label.grid(row=2, column=0)
DATE_Label = Label(root, text="Date")
DATE_Label.grid(row=3, column=0)
TIME_Label = Label(root, text="Time")
TIME_Label.grid(row=4, column=0)
CHART_VALUE_Label = Label(root, text="Chart Value")
CHART_VALUE_Label.grid(row=5, column=0)
button = Button(root, text = "Show All Values", command = showvalues)
button.grid(row=0, column=0)
button = Button(root, text = "Insert Values", command = insertvalue)
button.grid(row=1, column=0)
#Commit changes
conn.commit()
# Close connection
conn.close()
root.mainloop()
I used this format to insert data into a sqlite3 db, but the same format is not working when inserting into a SQL Server database. I have tested the connection to the SQL server and can display values in the app so that part works correctly.
Hi I am trying to create a db for a golf game I play with my son and am having some issues.
I keep getting the following error when trying to insert data into my db:
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')
Here is the code:
import tkinter as TK
from tkinter import *
import pyodbc
golfers=Tk()
golfers.title("Golfers")
golfers.geometry('500x500')
#Databases
#Create a Database or Connect to one
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-SCL1250\SQLEXPRESS01;'
'Database=tgt;'
'Trusted_Connection=yes;')
#Create Cursor
c=conn.cursor()
# c.execute("""CREATE TABLE tours(
# tour_code varchar NOT NULL,
# description varchar (255),
# PRIMARY KEY (tour_code))
# """)
# c.execute("""CREATE TABLE golfers (
# golfer_id int IDENTITY(1,1) NOT NULL,
# last_name varchar (255),
# first_name varchar (255),
# tour_code varchar FOREIGN KEY REFERENCES tours(tour_code)
# PRIMARY KEY (golfer_id))
# """)
def submit():
#Create a Database or Connect to one
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-SCL1250\SQLEXPRESS01;'
'Database=tgt;'
'Trusted_Connection=yes;')
#Create Cursor
c=conn.cursor()
#Insert into table
c.execute('INSERT INTO golfers VALUES(:golfer_id, :last_name, :first_name, :tour_code)',
{
'golfer_id': golfer_id.get(),
'last_name': last_name.get(),
'first_name': first_name.get(),
'tour_code': tour_code.get()
})
#Commit Changes
conn.commit()
#Close Connection
conn.close()
#clear the text boxes
golfer_id.delete(0,END)
last_name.delete(0, END)
first_name.delete(0, END)
tour_code.delete(0,END)
#Create Text Boxes
golfer_id = Entry(golfers, width=30)
golfer_id.grid(row=0, column=1, padx=20)
last_name = Entry(golfers, width=30)
last_name.grid(row=1, column=1, padx=20)
first_name = Entry(golfers, width=30)
first_name.grid(row=2, column=1, padx=20)
tour_code = Entry(golfers, width=30)
tour_code.grid(row=3, column=1, padx=20)
#Create Text Box Labels
golfer_id_label = Label(golfers, text="Golfer ID")
golfer_id_label.grid(row=0, column=0)
last_name_label = Label(golfers, text="Last Name")
last_name_label.grid(row=1, column=0)
first_name_label = Label(golfers, text="First Name")
first_name_label.grid(row=2, column=0)
tour_code_label = Label(golfers, text="Tour Code")
tour_code_label.grid(row=3, column=0)
#Create Submit Button
submit_btn = Button(golfers, text="Add Record", command=submit)
submit_btn.grid(row=6, columnspan=2, pady=10, padx=10, ipadx=100)
#Commit Changes
conn.commit()
#Close Connection
conn.close()
golfers.mainloop()
Any help would be appreciated.
I've been working on a password vault the past few days. Everything works fine, but my database doesn't work. The database is created but it doesn't store the email-adresses, usernames and passwords. Anybody knows what's wrong with my code? Code below.
Also this is the error I get everytime:
label = Label(window, text=(array[i][1]), font=("Helvetica", 12))
IndexError: list index out of range
#Databese Code
with sqlite3.connect("password_vault.db") as db:
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS masterpassword(
id INTEGER PRIMARY KEY,
password TEXT NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS vault(
id INTEGER PRIMARY KEY,
website TEXT NOT NULL,
username TEXT NOT NULL,
password TEXT NOT NULL
)
""")
def passwordVault():
for widget in window.winfo_children():
widget.destroy()
def addEntry():
text1 = "Website"
text2 = "Username"
text3 = "Password"
website = popUp(text1)
username = popUp(text2)
password = popUp(text3)
insert_fields = """INSERT INTO vault(website,username,password)
VALUES(?, ?, ?)"""
cursor.execute(insert_fields, (website, username, password))
db.commit
passwordVault()
cursor.execute("SELECT * FROM vault")
if (cursor.fetchall() != None):
i = 0
while True:
cursor.execute("SELECT * FROM vault")
array = cursor.fetchall()
label = Label(window, text=(array[i][1]), font=("Helvetica", 12))
label.grid(column=0, row=i+3)
label = Label(window, text=(array[i][2]), font=("Helvetica", 12))
label.grid(column=1, row=i+3)
label = Label(window, text=(array[i][3]), font=("Helvetica", 12))
label.grid(column=2, row=i+3)
btn = Button(window, text="Delete", command= partial(removeEntry, array[i][0]))
btn.grid(column=3, row=i+3, pady=10)
i += 1
cursor.execute("SELECT * FROM vault")
if (len(cursor.fetchall()) <= i):
break
It may be as simple as the fact you are using colons, not semi-colons to end your script. Python uses Semi-colons to end all functions. Not to mention, it appears there is no command for actually having those passwords, I.E. those passwords are not in your code to be accessed, as well as there is no function for the email addresses, of which you will also have to insert manually. Let me know if you need anything else.
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.
I am writing a function to delete a record from a table. The variable I am trying to refer to in the delete statement is a Tkinter entry field.
I get the variable using the .get() method, but I can't then pass this into the SQLite statment without returning an error.
The following code is part of the frame, I've only added the relevant code to the problem
from tkinter import *
import sqlite3
class EditOrdersForm(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Edit Orders form:")
self.pack()
def displayDelOrderOptions(self):
self.deleteOrderOptionsLabel = Label(self, text="Enter the Order ID of the order you wish to delete: ").grid(row=numOrders+4, pady=2, sticky=W)
self.deleteOrderOptionsEntry = Entry(self, bd=3, width=10)
self.deleteOrderOptionsEntry.grid(row=numOrders+4, pady=5, column=1)
global orderToDelete
orderToDelete = self.deleteOrderOptionsEntry.get()
self.deleteButton = Button(self, text = "Delete this order", command = self.deleteOrder)
self.deleteButton.grid(row=numOrders+5, pady=5, column=1)
def deleteOrder(self):
conn = sqlite3.connect("testdb.db")
c = conn.cursor()
c.execute("DELETE FROM orders WHERE orders_id=:1)", (orderToDelete,))
conn.commit
c.close()
root = EditOrdersForm()
root.mainloop()
The problem I have is with the WHERE statement, how do I refer to orderToDelete. I have tried converting it to a string and using (?) as the parameter but this didn't work either.
THe correct syntax for parameterized query is:
c.execute("DELETE FROM orders WHERE orders_id=?)", (orderToDelete,))
I believe you just need to call commit instead of reference it
conn.commit()