Steps For Implementing CRUD Operations in Python Using Tkinter With MySQL
Steps For Implementing CRUD Operations in Python Using Tkinter With MySQL
First, we’ll design our GUI application, you can follow below source code to use in
your python script:
Python Code:
from tkinter import *
import tkinter.messagebox as MessageBox
import mysql.connector as mysql
root = Tk()
root.geometry("500x300")
root.title("MySQL CRUD Operations")
id = Label(root, text="Enter ID:", font=("verdana 15"))
id.place(x=50, y=30)
id_entry = Entry(root, font=("verdana 15"))
id_entry.place(x=150, y=30)
root.mainloop()
Now that we have created our GUI App, we’ll write a code for MySQL connection and perform
CRUD operations. I’ve provided the source code for Insert, Update, Delete, and Select functions.
INSERT Function
def Insert():
1
id = id_entry.get()
2
name = name_entry.get()
3
phone = phone_entry.get()
4
5
if(id == "" or name == "" or phone == ""):
6
MessageBox.showinfo("ALERT", "Please enter all fields")
7
else:
8
con = mysql.connect(host="localhost", user="Database Username",
9
password="Your Database Password", database="Your Database Name")
10
cursor = con.cursor()
11
cursor.execute("insert into Person values('" + id +"', '"+ name +"', '" + phone +"')")
12
cursor.execute("commit")
13
14
MessageBox.showinfo("Status", "Successfully Inserted")
15
con.close();
INSERT Function
1 def Insert():
2 id = id_entry.get()
3 name = name_entry.get()
4 phone = phone_entry.get()
5
6 if(id == "" or name == "" or phone == ""):
7 MessageBox.showinfo("ALERT", "Please enter all fields")
8 else:
9 con = mysql.connect(host="localhost", user="Database Username",
10 password="Your Database Password", database="Your Database Name")
11 cursor = con.cursor()
12 cursor.execute("insert into Person values('" + id +"', '"+ name +"', '" + phone +"')")
13 cursor.execute("commit")
14
15 MessageBox.showinfo("Status", "Successfully Inserted")
con.close();
DELETE Function
def Del():
1
2
if(id_entry.get() == ""):
3
MessageBox.showinfo("ALERT", "Please enter ID to delete row")
4
else:
5
con = mysql.connect(host="localhost", user="Database Username",
6
password="Your Database Password", database="Your Database Name")
7
cursor = con.cursor()
8
cursor.execute("delete from Person where id='"+ id_entry.get() +"'")
9
cursor.execute("commit");
10
11
id_entry.delete(0, 'end')
12
name_entry.delete(0, 'end')
13
phone_entry.delete(0, 'end')
14
15
MessageBox.showinfo("Status", "Successfully Deleted")
16
con.close();
SELECT Function
1 def Select():
2
3 if(id_entry.get() == ""):
4 MessageBox.showinfo("ALERT","ID is required to select row!")
5 else:
6 con = mysql.connect(host="localhost", user="Database Username",
7 password="Your Database Password", database="Your Database Name")
8 cursor = con.cursor()
9 cursor.execute("select * from Person where id= '" + id_entry.get() +"'")
10 rows = cursor.fetchall()
11
12 for row in rows:
13 name_entry.insert(0, row[1])
14 phone_entry.insert(0, row[2])
15
con.close();