JavaScript
x
48
48
1
from tkinter import *
2
import tkinter as tk
3
from tkinter import filedialog
4
import mysql.connector
5
from tkinter import messagebox, simpledialog
6
from tkinter.messagebox import askokcancel, showinfo, WARNING
7
8
db = mysql.connector.connect(
9
host="localhost",
10
user="admin",
11
passwd="test",
12
database="dbpath"
13
)
14
15
mycursor = db.cursor()
16
17
mycursor.execute("CREATE DATABASE IF NOT EXISTS dbpath")
18
mycursor.execute(
19
"CREATE TABLE IF NOT EXISTS filepaths (id INT AUTO_INCREMENT PRIMARY KEY, path VARCHAR(255), name VARCHAR(255))")
20
21
22
def confirmDeleteOne():
23
ROOT = tk.Tk()
24
ROOT.withdraw()
25
26
USER_INP = simpledialog.askstring(title="App Name",
27
prompt="Insert the name of the app you want delete:")
28
answer = askokcancel(
29
title='DELETION',
30
message='Are you sure?nTHIS IS AN IRREVERSIBLE ACTION',
31
icon=WARNING)
32
33
if answer:
34
mycursor.execute("DELETE FROM filepaths WHERE name = '" + USER_INP + "';")
35
db.commit()
36
showinfo(
37
title='DELETION',
38
message='SUCCESSFULLY DELETED ' + USER_INP.upper())
39
40
41
root = Tk()
42
43
44
deleteOne = Button(root, text="Delete One", command=confirmDeleteOne, bg='yellow', font="bold")
45
deleteOne.pack()
46
47
root.mainloop()
48
The problem that I am refering to is that if you insert something random in the USER_INP
variable that is not in the database, it doesn’t show an error like THIS DOES NOT EXIST IN THE TABLE
or something like that. What I want to achieve is when the user inserts something random in the USER_INP
variable, the last message that should be displayed is
message='THIS DOES NOT EXIST IN THE TABLE '
Advertisement
Answer
SQL doesn’t generate an error if a WHERE
clause doesn’t match anything, it just doesn’t do anything. In a SELECT
query it returns an empty result set; in a DELETE
or UPDATE
it doesn’t change anything.
You can use the rowcount
attribute to find out how many rows were deleted. If this is 0
you can display an error message.
JavaScript
1
11
11
1
if answer:
2
mycursor.execute("DELETE FROM filepaths WHERE name = %s", (USER_INP,))
3
if mycursor.rowcount == 0:
4
msg = 'THIS DOES NOT EXIST IN THE TABLE'
5
else:
6
msg = 'SUCCESSFULLY DELETED ' + USER_INP.upper()
7
db.commit()
8
showinfo(
9
title='DELETION',
10
message=msg)
11