import mysql.connector # Import the MySQL connector library
my_connect = mysql.connector.connect(
host="localhost", # Hostname of the MySQL server
user="userid", # User ID for authentication
passwd="password", # Password for the user
database="database_name" # Name of the database to connect to
)
####### end of connection credentials ####
my_cursor = my_connect.cursor() # Initialize the cursor object for executing queries
We will use my_cursor in our further script as the connection object to get our records.
l1 = tk.Label(my_w, text='Enter Student ID: ', font=['Arial', 10])
l1.grid(row=1, column=1) # Position the label at row 1, column 1
t1 = tk.Entry(my_w, width=4, bg='yellow', font=['Arial', 18])
t1.grid(row=1, column=2) # Position the entry box at row 1, column 2
We need one more Label ( l2) to display the returned details of the student. This Label initially will display the string Output. my_str = tk.StringVar() # Create a StringVar object
l2 = tk.Label(my_w, textvariable=my_str, width=30, fg='red')
l2.grid(row=3, column=1, columnspan=2) # Position the label in the grid
my_str.set('Output') # Assign a default string value
We will add one Button b1 to pass user entered data to a function to get the record details.
b1 = tk.Button(my_w, text='Show Details',font=['Arial',14],width=10,bg='red',
command=lambda: my_details(t1.get()))
b1.grid(row=1,column=3,padx=3)
try:
val = int(id) # check input is integer or not
my_data = (val,)
except:
my_str.set("Check input")
Inside the try block ( the input id is integer ) we will keep one more try and except. In this try block we will keep the database handling part and in except block we will display message Database error. The full code of the function my_details() is here.
def my_details(id):
try:
val = int(id) # check input is integer or not
my_data = (val,)
try:
query = 'SELECT * FROM student WHERE id=%s'
my_cursor.execute(query, my_data)
student = my_cursor.fetchone()
#print(student)
my_str.set(student)
except:
my_str.set('Database error')
except:
my_str.set('Check input')
We used SQL with WHERE to collect details of the record by using student id from the student table.
import mysql.connector
import tkinter as tk
from tkinter import *
my_connect = mysql.connector.connect(
host="localhost",
user="id",
passwd="password",
database="db_name"
)
my_cursor = my_connect.cursor()
####### end of connection ####
my_w = tk.Tk()
my_w.geometry("400x200")
# add one Label
l1 = tk.Label(my_w, text='Enter Student ID: ',font=['Arial',10] )
l1.grid(row=1,column=1)
t1 = tk.Entry(my_w, width=4,bg='yellow',font=['Arial',18])
t1.grid(row=1,column=2)
b1 = tk.Button(my_w, text='Show Details', font=['Arial',14], width=10,bg='red',
command=lambda: my_details(t1.get()))
b1.grid(row=1,column=3,padx=3)
my_str = tk.StringVar()
my_str.set('Output here ')
# add one Label
l2 = tk.Label(my_w, textvariable=my_str, width=30,fg='red', font=['Arial',18])
l2.grid(row=3,column=1,columnspan=3,pady=10)
my_str.set("Output")
def my_details(id):
try:
val = int(id) # check input is integer or not
my_data=(val,)
try:
query = "SELECT * FROM student WHERE id=%s"
my_cursor.execute(query,my_data)
student = my_cursor.fetchone()
#print(student)
my_str.set(student)
except :
my_str.set("Database error")
except:
my_str.set("Check input")
my_w.mainloop()
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_db") # mysql credentials
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
my_w.geometry("400x250")
l1 = tk.Label(my_w, text='Enter Student ID: ',font=['Arial',10] )
l1.grid(row=1,column=1)
t1 = tk.Entry(my_w, width=4,bg='yellow',font=['Arial',18])
t1.grid(row=1,column=2)
b1 = tk.Button(my_w, text='Show Details', font=['Arial',14], width=10,bg='red',
command=lambda: my_details(t1.get()))
b1.grid(row=1,column=3,padx=5)
my_str = tk.StringVar()
my_str.set('Output here ')
# add one Label
l2 = tk.Label(my_w, textvariable=my_str, width=30,fg='red', font=['Arial',18])
l2.grid(row=3,column=1,columnspan=3,pady=10)
from sqlalchemy import create_engine,text
from sqlalchemy.exc import SQLAlchemyError
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_db") # mysql credentials
my_conn = my_conn.connect()
def my_details(id):
try:
id = int(id) # check input is integer or not
try:
my_data={'my_id':id} # dicitionary with place holder and value
my_row=my_conn.execute(text("SELECT * FROM student WHERE id=:my_id"),my_data)
student = my_row.fetchone()
#print(student)
my_str.set(student)
except SQLAlchemyError as e:
error = str(e.__dict__.get('orig', e)) # get error message
print(error)
except:
my_str.set("Check input")
my_w.mainloop()
import tkinter as tk
from tkinter import ttk # required for Treeview
from tkinter import *
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError # for database errors handling
my_w = tk.Tk()
my_w.geometry("400x250")
l1 = tk.Label(my_w, text='Enter Student ID: ', width=25)
l1.grid(row=1, column=1)
e1 = tk.Entry(my_w, width=4, bg='yellow', font=22)
e1.grid(row=1, column=2, padx=5)
b1 = tk.Button(my_w, text='Show Details', width=15, bg='red',
command=lambda: my_details(e1.get()))
b1.grid(row=1, column=3, padx=5, pady=20)
my_str = tk.StringVar(value='Output here')
# add one Label
l2 = tk.Label(my_w, textvariable=my_str, width=30, fg='red', font=16)
l2.grid(row=2, column=1, columnspan=3)
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_db")
my_conn = my_conn.connect()
# Global variable to track the Treeview widget
treeview_widget = None
def my_details(id):
global treeview_widget
try:
val = int(id) # Check input is an integer
my_data = {'my_id': id} # Dictionary with placeholder and value
query = "SELECT * FROM student WHERE id=:my_id" # Parameterized query
my_row = my_conn.execute(text(query), my_data)
row = my_row.fetchone() # Fetch the first row
# Clear the previously displayed Treeview, if any
if treeview_widget:
treeview_widget.destroy()
treeview_widget = None
if row:
student = list(row) # Convert tuple to list
my_str.set(student) # Display the row data in Label
l1 = [r for r in my_row.keys()] # List of column headers
# Create and display the new Treeview
treeview_widget = ttk.Treeview(my_w, selectmode='browse')
treeview_widget.grid(row=4, column=1, columnspan=4, padx=5, pady=20)
treeview_widget['height'] = 3 # Number of rows to display, default is 10
treeview_widget['columns'] = l1 # List of columns to display
treeview_widget['show'] = 'headings'
for i in l1:
treeview_widget.column(i, anchor='c', width=70)
treeview_widget.heading(i, text=i)
treeview_widget.insert("", 'end', iid=0, values=student) # Add data
else:
my_str.set("No data found for the given ID.") # Message if no data
except ValueError:
my_str.set("Invalid ID. Please enter a number.") # Input error handling
except SQLAlchemyError as e:
my_str.set(f"Database error: {e}") # Database error handling
my_w.mainloop()
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.