PYTHON SQLITE3 DELETE FROM LIST - function

I want to delete data from selected in ListBox. I tried everything but it's not working. I tried in simple file. It worked. I wrote same code here but it's not working. I'm stuck since two days. Please help.
from tkinter import *
import sqlite3
from tkinter import messagebox
import randevuEkleme as fRE
from tkcalendar import *
def randevularFormunuAc():
root = Tk()
root.title("Randevu Listesi Formu")
root.geometry("750x500")
randevuListesi = Listbox(root, width=50, bg="yellow", selectmode=SINGLE)
takvim = Calendar(root, selectmode="day", year=2020, month=5, day=22)
takvim.grid(row=0, column=0)
randevuListesi.grid(row=1, column=0)
secilen = randevuListesi.curselection()
def randevulariListele(): #OK!
con = sqlite3.connect('veri2.db')
c = con.cursor()
c.execute("SELECT * FROM randevular")
liste = c.fetchall()
con.commit()
con.close()
randevuListesi.delete(first=0,last=END)
for i in liste:
randevuListesi.insert(END,i)
con = sqlite3.connect('veri2.db')
c = con.cursor()
c.execute("SELECT * FROM randevular")
liste = c.fetchall()
con.commit()
con.close()
for i in liste:
randevuListesi.insert(END, i)
def randevuSil():
con = sqlite3.connect('veri2.db')
c = con.cursor()
# Problem is HERE!!!
c.execute("DELETE FROM randevular WHERE rowid = (?)", (secilen[0] + 1,))
# PROBLEMIS HERE!!!
con.commit()
con.close()
btnListele = Button(root, text="Randevuları Listele",command=randevulariListele)
btnRandevuEkle = Button(root,text="Randevu Ekle",command=fRE.randevuEklemeFormunuAc)
btnRandevuSil = Button(root,text="Randevuyu Sil",command=randevuSil()) !!!!
btnCikis = Button(root, text="Geri", command=root.quit)
btnListele.grid(row=2,column=0)
btnRandevuEkle.grid(row=2,column=1)
btnRandevuSil.grid(row=2,column=2)
btnCikis.grid(row=2,column=3)
root.mainloop()
and error message is :
File "C:\Users\kutla\PycharmProjects\fizyoOta1.0\randevularFormu.py", line 43, in randevuSil
c.execute("DELETE FROM randevular WHERE rowid = (?)", (secilen[0] + 1,))
IndexError: tuple index out of range

Two possibilities on a quick read:
The line secilen = randevuListesi.curselection() probably needs to be in randevuSil() rather than as part of the setup.
When setting up the button, the () should be omitted in the command=:
btnRandevuSil = Button(root,text="Randevuyu Sil",command=randevuSil)
Otherwise the function will be called as part of setup (when nothing has been selected yet) rather than when the button is clicked.

Related

Getting Image from MySQL into tableWidget in PyQt5

I have been able to get data from database and populate into the tableWidget, but the image column is not shown. I tried a code I found online and still, it didn't work. The image column in the database has the BLOB data type. Kindly assist in correcting my following code. Or you may want to advise and recommend another method other than the tableWidget
def getPersData(self):
con = MySQLdb.connect(host="localhost", user="root", password="", database="db")
with con:
cur = con.cursor()
query = cur.execute("SELECT * FROM persons")
rows = cur.fetchall()
for row_number, row_data in enumerate(rows):
self.ui.tableWidget.insertRow(row_number)
for column_number, column_data in enumerate(row_data):
if column_number == 1:
item = self.getImg(column_data)
self.ui.tableWidget.setCellWidget(row_number, column_number, item)
else:
self.ui.tableWidget.setItem(row_number, column_number, QTableWidgetItem(str(column_data)))
self.ui.tableWidget.verticalHeader().setDefaultSectionSize(100)
self.ui.tableWidget.show()
def getImg(self, img):
img_label = self.ui.label
img_label.setText("")
img_label.setScaledContents(True)
pixmap = QPixmap()
pixmap.loadFromData(img, "PNG")
img_label.setPixmap(pixmap)
return img_label
The logic to use the bytes (in my previous answer I proposed to use base64 so I use it in this case as well) to build a QPixmap that can be converted into a QIcon that can be displayed in the QTableWidget:
for row_number, row_data in enumerate(rows):
self.ui.tableWidget.insertRow(row_number)
for column_number, column_data in enumerate(row_data):
it = QTableWidgetItem()
if column_number == 1:
pixmap = QPixmap()
pixmap.loadFromData(QByteArray.fromBase64(row_data))
icon = QIcon(pixmap)
it.setIcon(icon)
else:
it.setText(row_data)
self.ui.tableWidget.setItem(row_number, column_number, it)

Question marks while fetching data from phpmyadmin in Python 3

Hello I have win 10 Greece. I want to fetch same data (the path of a file) from mysql. The problem is while I retrieve the path instead of the name of the folder I came across with??????. A sample of the code is the following
import pymysql as MySQLdb
dbid = "client"
password = "pass"
database = "clients"
serverip = "192.168.168.150"
db = None
cur = None
try:
db = MySQLdb.connect(host=serverip, user=dbid, passwd=password, db=database, connect_timeout=20)
cur = db.cursor()
except MySQLdb.Error as e:
print("Cannot connect with the Data Base : "), e
query1 = "SELECT path FROM `instructions` WHERE clientmac ='%s'" % (str(5555))
try:
row = None
cur.execute(query1)
db.commit()
row = cur.fetchall()
except MySQLdb.Error as e:
print("Problem while Executing query :", query1, "error : ", e)
print(row)
db.close()
cur.close()
Python 3 uses Unicode so I thing that the problem is not from python but from phpmyadmin. The field path is “utf8_general_ci”. Everything looks fine but why instead of
'C:\\Users\\Γιαννης\\Documents\\Arduino' I am getting 'C:\\Users\\???????\\Documents\\Arduino'
I found the answer. I hat to but some additional coding before the execution of the query. I post the code below.
import pymysql as MySQLdb
dbid = "client"
password = "pass"
database = "clients"
serverip = "192.168.168.150"
socketip = "192.168.168.18"
db = None
cur = None
try:
db = MySQLdb.connect(host=serverip, user=dbid, passwd=password, db=database, use_unicode=True, connect_timeout=20)
cur = db.cursor()
except MySQLdb.Error as e:
print("Cannot connect with the Data Base : "), e
query1 = "SELECT path FROM `instructions` WHERE clientmac ='%s'" % (str(5555))
try:
row = None
db.set_charset('utf8')
cur.execute('SET NAMES utf8;')
cur.execute('SET CHARACTER SET utf8;')
cur.execute('SET character_set_connection=utf8;')
cur.execute(query1)
db.commit()
row = cur.fetchall()
except MySQLdb.Error as e:
print("Problem while Executing query :", query1, "error : ", e)
print(row)
db.close()
cur.close()

how to display data from MySql db to html pages in python

i want to display all the data in my table to a webpage using python when i click a button. here is my app.py code can anyone help me to finish this please..
def POST(self):
form = web.input(name="a", newname="s", number="d")
conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
x = conn.cursor()
x.execute("SELECT * FROM details")
conn.commit()
items = cursor.fetchall()
return items()
conn.rollback()
conn.close()
return render.index()
i want to display it on index.html.and table has 3 colums
def POST(self):
form = web.input(name="a", newname="s", number="d")
conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
x = conn.cursor()
x.execute("SELECT * FROM details")
conn.commit()
items = cursor.fetchall()
for row in items:
print row[0], row[1]
conn.rollback()
conn.close()
return render.index(items)
Run this code and check output in terminal and let me know the data is comming or not

Retrieving MySQL with Kivy

I have a Kivy code, where the output is:
I want to get replace the Box No. with strings retrieved from MySQL
So far I have tried to implement the MySQL to the python script:
class RemoveScreen(MyLayout):
def __init__(self,**kwargs):
db = MySQLdb.connect("localhost", "root", "[PASSWORD]", "tcs_microrage_crm")
cursor=db.cursor()
self.var = StringVar()
self.label1 = Label(self, text=0, textvariable=self.var)
myvar=str(self.var)
#http://stackoverflow.com/questions/775296/python-mysql-parameterized-queries
cursor.execute("SELECT part_name FROM stock_lists WHERE part_number = %s", (myvar))
self.myvar=StringVar()
self.myvar.set(cursor.fetchone())
self.label2 = Label(self, text=0, textvariable=myvar)
But this didn't work.
Q: How can I do MySQL queries and print individual strings in the kv file.
To show you how you could do that, I made a little search example.
This searches for fruit names in the database, and will output its name and price to the table.
from kivy.app import App
import MySQLdb
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
class DbCon:
def __init__(self):
self.db = MySQLdb.connect(user="root",passwd="pw",db="kivy")
self.c = self.db.cursor()
def get_rows(self,search = ""):
self.c.execute("SELECT * FROM fruit WHERE name REGEXP '.*%s.*' LIMIT 3" % search)
return self.c.fetchall()
class Table(BoxLayout):
def __init__(self,**kwargs):
super(Table,self).__init__(**kwargs)
self.orientation = "vertical"
self.search_field = BoxLayout(orientation="horizontal")
self.search_input = TextInput(text='search',multiline=False)
self.search_button = Button(text="search",on_press=self.search)
self.search_field.add_widget(self.search_input)
self.search_field.add_widget(self.search_button)
self.add_widget(self.search_field)
self.add_widget(Label(text="table"))
self.table = GridLayout(cols=2,rows=4)
self.table.add_widget(Label(text="Fruit"))
self.table.add_widget(Label(text="Price"))
self.rows = [[Label(text="item"),Label(text="price")],
[Label(text="item"),Label(text="price")],
[Label(text="item"),Label(text="price")]]
for item,price in self.rows:
self.table.add_widget(item)
self.table.add_widget(price)
self.add_widget(self.table)
self.db = DbCon()
self.update_table()
def update_table(self,search=""):
for index,row in enumerate(self.db.get_rows(search)):
self.rows[index][0].text = row[1]
self.rows[index][1].text = str(row[2])
def clear_table(self):
for index in range(3):
self.rows[index][0].text = ""
self.rows[index][1].text = ""
def search(self, *args):
self.clear_table()
self.update_table(self.search_input.text)
class MyApp(App):
def build(self):
return Table()
MyApp().run()

How can I escape the input to a MySQL db in Python3?

How can I escape the input to a MySQL db in Python3?
I'm using PyMySQL and works fine, but when I try to do something like:
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = '{}'".format(request[1]))
it won't work if the string has ' or ". I also tried:
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = %s",request[1])
The problem with this is that the library (PyMySQL) uses the formatting syntax for Python2.x, %, that doesn't work anymore.
I also found this possible solution
conn.escape_string()
in here, but I don't know where to add this code.
This is all I got:
import pymysql
import sys
conn = pymysql.connect( host = "localhost",
user = "test",
passwd = "",
db = "test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = {}".format(request[1]))
result = cursor.fetchall()
cursor.close()
conn.close()
Edit: I solved it! In PyMySQL the right way is like this:
import pymysql
import sys
conn = pymysql.connect(host="localhost",
user="test",
passwd="",
db="test")
cursor = conn.cursor()
text = conn.escape(request[1])
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = {}".format(text))
cursor.close()
conn.close()
Where the text = conn.escape(request[1]) line is what escapes the code. Found it inside PyMySQL code. There, request[1] is the input.
Although the "solved" answer works, it is not best practice. When using a library conforming to the Python DBI, you should be using bind variables rather than formatting a string and passing it to execute. There are dangers inherent in that methodology.
Therefore, this is the right way to do it:
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = %s", text)
Note that this is not a format string but a bind variable passed to the executing cursor.
For details: Python DBI PEP
Solved. In PyMySQL the right way is like this:
import pymysql
import sys
conn = pymysql.connect(host="localhost",
user="test",
passwd="",
db="test")
cursor = conn.cursor()
text = conn.escape(request[1])
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` = {}".format(text))
cursor.close()
conn.close()
Where the text = conn.escape(request[1]) line is what escapes the code. Found it inside PyMySQL code. There, request[1] is the input.
Ready to use helper function
def mysql_insert(conn, table, row):
cols = ', '.join('`{}`'.format(col) for col in row.keys())
vals = ', '.join('%({})s'.format(col) for col in row.keys())
sql = 'INSERT INTO `{0}` ({1}) VALUES ({2})'.format(table, cols, vals)
conn.cursor().execute(sql, row)
conn.commit()
Usage example
insert_into(conn, 'people', {
'firstname': 'John',
'lastname': 'Doe',
'age': 18, })
Reference: https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/cursors.py#L157-L158
def execute(self, query, args=None):
If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.