I have defined a function here and it is supposed to work correctly because im using a similar function somewhere else but without giving any conditions(where.. like or regexp) and it works fine there, when i use regexp and all it does not give an output. Why is that? Thanks in advance :)
Code:
def search():
log = Toplevel(root)
log.title('View all customers')
def db():
selected = drop.get()
result_win = Toplevel(log)
result_win.title('Search result')
con = mysql.connect(host='localhost', user='root',
password='*****', database='BOOK')
c = con.cursor()
c.execute(f"SELECT * from books where '{selected}' regexp
'{e_sch.get()}';")
result = c.fetchall()
index=0
for index, x in enumerate(result):
num = 0
for y in x:
lookup_label = Label(result_win, text=y)
lookup_label.grid(row=index+1, column=num)
num +=1
con.close()
l1 = Label(result_win,text='Sl.No',font=font_text)
l2 = Label(result_win,text='Title',font=font_text)
l3 = Label(result_win,text='Authors',font=font_text)
l4 = Label(result_win,text='Subject',font=font_text)
l5 = Label(result_win,text='Availablity',font=font_text)
btn_ext = Button(result_win,text='Exit',font=font_text,command=result_win.destroy,borderwidth=2,fg='#eb4d4b')
l1.grid(row=0,column=0,padx=20)
l2.grid(row=0,column=1,padx=20)
l3.grid(row=0,column=2,padx=20)
l4.grid(row=0,column=3,padx=20)
l5.grid(row=0,column=4,padx=20)
btn_ext.grid(row=index+2,columnspan=7,ipadx=540)
global a
l = Label(log,text='Search',font=Font(family='helvetica', size='20'))
drop = ttk.Combobox(log,value=['Search by....','Sl.no','Title','Authors','Subject','Availablity'])
drop.current(0)
l2 = Label(log,text='Enter',font=font_text)
e_sch = Entry(log)
b_sch = Button(log, text='Search book', command=db, font=font_text)
b_ext = Button(log, text='Exit', command=log.destroy, font=font_text)
a = drop.get()
l.grid(row=0,columnspan=3,pady=20)
drop.grid(row=1,column=0,columnspan=3)
l2.grid(row=2,column=0,padx=(20,0))
e_sch.grid(row=2,column=1, padx=30, ipady=5,pady=20)
b_sch.grid(row=3,column=0,columnspan=3,ipadx=200)
b_ext.grid(row=4,column=0,columnspan=3,ipadx=237)
Sometimes i get this error too UnboundLocalError: local variable 'index' referenced before assignment
The syntax of the SELECT statement is incorrect:
SELECT * from books where '{selected}' regexp '{e_sch.get()}';
should be:
SELECT * from books where `{selected}` regexp '{e_sch.get()}';
Field name should be surrounded by ``, not ''.
Related
I'm unable to update my table in MySQL using Tkinter. It just won't get updated. I have tried checking where the table name is different but it's not. It shows no errors but not getting updated.
from tkinter import *
t = Tk()
t.geometry("500x500")
Label(text = 'Name:').place(x=10,y=10)
nm = Entry()
nm.place(x=55,y=12)
Label(text = 'age:').place(x=10,y=35)
ag = Entry()
ag.place(x=55,y=37)
def abcd():
import pymysql
x = pymysql.connect(host = 'localhost',user = 'root',password = 'admin',db ='db')
cur = x.cursor()
n= nm.get()
a = ag.get()
cur.execute('insert into sample2 values(%s, %s)',(n,a))
x.commit()
x.close()
Button(text ='Submit',command = abcd).place(x=40,y=65)
Label(text ='UPDATE',fg = 'white',bg = 'black',font = ('Times new roman',24,'bold')).place(x=10,y=100)
Label(text ='Enter the name to update').place(x = 5,y = 155)
b=Entry()
b.place(x = 150, y = 157)
Label(text = 'Enter new age:').place(x=5,y = 200)
nag = Entry()
nag.place(x=150,y = 202)
'''print(b)'''
def upd():
import pymysql
x = pymysql.connect(host = 'localhost',user = 'root',password = 'admin',db ='db')
cur = x.cursor()
gnd =b.get()
anag = nag.get()
cur.execute('update sample2 set age =%s where name = %s',(gnd,anag))
x.commit()
x.close()
t.mainloop()
Button(text = 'apply',command = upd).place(x = 200, y = 300)
t.mainloop()
It is because the order of the arguments used in UPDATE is wrong:
cur.execute('update sample2 set age =%s where name = %s',(gnd,anag)) # wrong order of arguments
So the WHERE clause is evaluated as False and no record will be updated.
It should be:
cur.execute('update sample2 set age =%s where name = %s',(anag, gnd))
I am trying to have python pull each row of the database into its own button and then run the code contained within that blob when the button is clicked.
The exec function is not executing the code pulled from the database, it successfully prints everytime as I added this to assist with debugging but never actually runs the code contained within the blob.
Problem code:
def run_file(fName):
connectiondb = mysql.connector.connect(user='admin', password='admin', host='localhost', database='cypilearning')
cursordb = connectiondb.cursor()
cursordb.execute("SELECT filedata FROM cyberphysicalsystems WHERE name = %s", [(fName)])
r = cursordb.fetchall()
for i in r:
data = i[0]
decodedData = data.decode("utf8")
tk.messagebox.showinfo(fName, decodedData)
exec(decodedData)
connectiondb.commit()
connectiondb.close()
def check_files():
connectiondb = mysql.connector.connect(user='admin', password='admin', host='localhost', database='cypilearning')
cursordb = connectiondb.cursor()
cursordb.execute("SELECT name FROM cyberphysicalsystems")
r = cursordb.fetchall()
startX = 25
startY = 275
j = 0
for i in r:
button = Button(self, text=i, width=15)
button.configure(bg="#83B4B3", activebackground="#097392", command=lambda i=i: run_file(i[0]))
button.place(x=startX, y=startY)
startX = startX+200
j = j+1
if j == 6:
startY = startY+100
startX = 25
j = 0
connectiondb.commit()
connectiondb.close()
#imports
from tkinter import *
from tkinter import messagebox as ms
import sqlite3
# make database and users (if not exists already) table at programme start up
with sqlite3.connect('quit.db') as db:
c = db.cursor()
c.execute('CREATE TABLE IF NOT EXISTS user (username TEXT NOT NULL ,password TEX NOT NULL);')
db.commit()
db.close()
#main Class
class main:
def __init__(self,master):
# Window
self.master = master
# Some Usefull variables
self.username = StringVar()
self.password = StringVar()
self.n_username = StringVar()
self.n_password = StringVar()
#Create Widgets
self.widgets()
def NewPage():
global NewRoot
root.withdraw() # hide (close) the root/Tk window
NewRoot = tk.Toplevel(root)
# use the NewRoot as the root now
#Login Function
def login(self):
with sqlite3.connect('quit.db') as db:
c = db.cursor()
#Find user If there is any take proper action
find_user = ('SELECT * FROM user WHERE username = ? and password = ?')
c.execute(find_user,[(self.username.get()),(self.password.get())])
result = c.fetchall()
if result:
self.logf.pack_forget()
self.head['text'] = self.username.get() + '\n Logged In'
self.head['pady'] = 150
root.after(2000, NewPage)
else:
ms.showerror('Oops!','Username Not Found.')
def new_user(self):
#Establish Connection
with sqlite3.connect('quit.db') as db:
c = db.cursor()
#Find Existing username if any take proper action
find_user = ('SELECT * FROM user WHERE username = ?')
c.execute(find_user,[(self.username.get())])
if c.fetchall():
ms.showerror('Error!','Username Taken Try a Diffrent One.')
else:
ms.showinfo('Success!','Account Created!')
self.log()
#Create New Account
insert = 'INSERT INTO user(username,password) VALUES(?,?)'
c.execute(insert,[(self.n_username.get()),(self.n_password.get())])
db.commit()
#Frame Packing Methords
def log(self):
self.username.set('')
self.password.set('')
self.crf.pack_forget()
self.head['text'] = 'LOGIN'
self.logf.pack()
def cr(self):
self.n_username.set('')
self.n_password.set('')
self.logf.pack_forget()
self.head['text'] = 'Create Account'
self.crf.pack()
#Draw Widgets
def widgets(self):
self.head = Label(self.master,text = 'LOGIN',font = ('',35),pady = 10)
self.head.pack()
self.logf = Frame(self.master,padx =10,pady = 10)
Label(self.logf,text = 'Username: ',font = ('',20),pady=5,padx=5).grid(sticky = W)
Entry(self.logf,textvariable = self.username,bd = 5,font = ('',15)).grid(row=0,column=1)
Label(self.logf,text = 'Password: ',font = ('',20),pady=5,padx=5).grid(sticky = W)
Entry(self.logf,textvariable = self.password,bd = 5,font = ('',15),show = '*').grid(row=1,column=1)
Button(self.logf,text = ' Login ',bd = 3 ,font = ('',15),padx=5,pady=5,command=self.login).grid()
Button(self.logf,text = ' Create Account ',bd = 3 ,font = ('',15),padx=5,pady=5,command=self.cr).grid(row=2,column=1)
self.logf.pack()
self.crf = Frame(self.master,padx =10,pady = 10)
Label(self.crf,text = 'Username: ',font = ('',20),pady=5,padx=5).grid(sticky = W)
Entry(self.crf,textvariable = self.n_username,bd = 5,font = ('',15)).grid(row=0,column=1)
Label(self.crf,text = 'Password: ',font = ('',20),pady=5,padx=5).grid(sticky = W)
Entry(self.crf,textvariable = self.n_password,bd = 5,font = ('',15),show = '*').grid(row=1,column=1)
Button(self.crf,text = 'Create Account',bd = 3 ,font = ('',15),padx=5,pady=5,command=self.new_user).grid()
Button(self.crf,text = 'Go to Login',bd = 3 ,font = ('',15),padx=5,pady=5,command=self.log).grid(row=2,column=1)
if __name__ == '__main__':
#Create Object
#and setup window
root = Tk()
root.title('Login Form')
#root.geometry('400x350+300+300')
main(root)
root.mainloop()
On line 37 it says NewPage is not defined but I defined it on line 24, please help. this program is object oriented and im a student trying to complete this for my A-Level project. I dont understand alot of this code but any help would be much appreciated. Im a amateur when it comes to python/tkinter/sqlite but need this help otherwise I will fail my course because my teacher is not much help when it comes to programming
You are missing self in your function def NewPage(self): and go to the line which you have root.after(2000, NewPage) and replace it with root.after(2000, self.NewPage)
At first I thought this would be an easy program where I could learn a lot. But I'm stuck.
How can I ask diffrent questions all after eachother. I have tried some things I came up with but none of those work.
This is the first one, where I use a variable x to re-generate the question. This simply doesn't work.
# Laad de database
cnx = mysql.connector.connect(user='FransSchool', password='RandomPass',host='10.0.0.25', database='Overhoor')
cursor = cnx.cursor()
# Maak een grafische interface
gui = Tk()
gui.resizable(width=FALSE, height=FALSE)
# Verklaringen
def verify():
overify = antwoord.get()
if overify == Nederlandsevertaling:
oentry.delete(0,END)
x=0
else:
oentry.delete(0,END)
x = 0
antwoord = StringVar()
willekeurig = random.randint(0,9)
# Indexeer de database
query = "SELECT FRwoord, NLwoord FROM unite8app1 WHERE id=%s"
cursor.execute(query, (willekeurig,))
while x < 1:
for (FRwoord, NLwoord) in cursor:
Fransevertaling = FRwoord
Nederlandsevertaling = NLwoord
x+=1
And this is the second one which gave me an error. It didn't really came as a surprise that this one didn't work. On button press it tries to recieve a new FR and NLwoord.
# Laad de database
cnx = mysql.connector.connect(user='FransSchool', password='RandomPass', host='10.0.0.25', database='Overhoor')
cursor = cnx.cursor()
# Maak een grafische interface
gui = Tk()
gui.resizable(width=FALSE, height=FALSE)
# Verklaringen
def verify():
overify = antwoord.get()
if overify == Nederlandsevertaling:
oentry.delete(0,END)
willekeurig = random.randint(0,9)
for (FRwoord, NLwoord) in cursor:
Fransevertaling = FRwoord
Nederlandsevertaling = NLwoord
else:
oentry.delete(0,END)
#Save the wrong answer aswell as the right answer to print out at the end
antwoord = StringVar()
willekeurig = random.randint(0,9)
# Indexeer de database
query = "SELECT FRwoord, NLwoord FROM unite8app1 WHERE id=%s"
cursor.execute(query, (willekeurig,))
for (FRwoord, NLwoord) in cursor:
Fransevertaling = FRwoord
Nederlandsevertaling = NLwoord
# Uiterlijk van het venster
gui.configure(background="white")
gui.title("Overhoorprogramma - Bryan")
# Grafische objecten
style = ttk.Style()
olabel = ttk.Label(gui,text=Fransevertaling,font=("Times", 18), background="white")
olabel.grid(row=0, column=0,padx=5, pady=5, sticky="W")
oentry = ttk.Entry(gui,textvariable=antwoord, font=("Times", 18))
oentry.grid(row=1, column=0,padx=5, pady=5)
obutton = ttk.Button(gui,text="Suivant", command = verify)
obutton.grid(row=1, column=1,padx=5, pady=5)
At the moment it just clears the entry box on button press. The goal is that everytime an answer has been typed in right it should skip that and if it is typed wrong it has to save it. Either way it has to create a new question what means a new Frword and NLword.
Ideally I am looking for a push in the right direction, the mechanism behind it or a small snippet of code.
Please Help me. I'm running a simple python program that will display the data from mySQL database in a tkinter form...
from Tkinter import *
import MySQLdb
def button_click():
root.destroy()
root = Tk()
root.geometry("600x500+10+10")
root.title("Ariba")
myContainer = Frame(root)
myContainer.pack(side=TOP, expand=YES, fill=BOTH)
db = MySQLdb.connect ("localhost","root","","chocoholics")
s = "Select * from member"
cursor = db.cursor()
cursor.execute(s)
rows = cursor.fetchall()
x = rows[1][1] + " " + rows[1][2]
myLabel1 = Label(myContainer, text = x)
y = rows[2][1] + " " + rows[2][2]
myLabel2 = Label(myContainer, text = y)
btn = Button(myContainer, text = "Quit", command=button_click, height=1, width=6)
myLabel1.pack(side=TOP, expand=NO, fill=BOTH)
myLabel2.pack(side=TOP, expand=NO, fill=BOTH)
btn.pack(side=TOP, expand=YES, fill=NONE)
Thats the whole program....
The error was
x = rows[1][1] + " " + rows[1][2]
IndexError: tuple index out of range
y = rows[2][1] + " " + rows[2][2]
IndexError: tuple index out of range
Can anyone help me??? im new in python.
Thank you so much....
Probably one of the indices is wrong, either the inner one or the outer one.
I suspect you meant to say [0] where you said [1], and [1] where you said [2]. Indices are 0-based in Python.
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.
This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.
I received the same error with
query = "INSERT INTO table(field1, field2,...) VALUES (%s,%s,...)"
but in the statement
cursor.execute(query, (field1, field2,..)
I had delivered less variables as necessary...
In this case I used
import mysql.connector as mysql
I just wanted to say that this is also possible...not only in arrays
(I didn't have a very close look at this specific case...)