How to Search data from SQLite in Python Tkinter | SQLite3 in Python

Hello friends how are you, Today in this post "How to Search data from SQLite in Python" you will learn that how you can create database in python, store data in database , display data in Python tkinter GUI interface and search particular data from SQLite and display in GUI interface. If you want to create a GUI Application in python using Database then this post will help you definitely. if you don't know how to handle SQLite in Python then i will suggest you first visit the below links if you want to be master in programming😊.

Complete SQLite with Python
Insert data into SQLite using Python tkinter
Fetch and Display data from SQLite
Now i am going to explain everything step by step
Step 1:Create Database 
The first step is to create database and here i am going to create a database with name student. Open or Create any python file and and type the following code to create SQLite database.

import  sqlite3
conn=sqlite3.connect("student.db")
print("Database created successfully")

Step 2:Create Table
Now the second step is to create table inside database and there is no need to create a separate python file to do this you can run these programs in same python file .So Just type the following code into your python file and run this code to create table STUD_REGISTRATION inside your student database. 

import  sqlite3
conn=sqlite3.connect("student.db")
print("Database Opened successfully")
conn.execute("""
CREATE TABLE STUD_REGISTRATION(
STU_ID INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,
STU_NAME TEXT NOT NULL, 
STU_CONTACT TEXT,
STU_EMAIL TEXT,
STU_ROLLNO TEXT NOT NULL,
STU_BRANCH TEXT NOT NULL)
""")
print ("Table STUD_REGISTRATION created successfully")
"""
###Output###
Database Opened successfully
Table STUD_REGISTRATION created successfully
"""

Here execute() is a predefined function which is used to execute any query of SQLite. 

Step 3:Insert data into table
Now its time to insert some records into our database so we can perform search operation on it. Here i am inserting two records into table but you can insert as many as you can. Following is the code to insert data into table.

import  sqlite3
conn=sqlite3.connect("student.db")
print("Database Opened successfully")

conn.execute("INSERT INTO STUD_REGISTRATION (STU_NAME,STU_CONTACT,STU_EMAIL,STU_ROLLNO,STU_BRANCH) \
      VALUES ('Raju', '9179876567', 'raju@gmail.com','MCA204', 'CA')");

conn.execute("INSERT INTO STUD_REGISTRATION (STU_NAME,STU_CONTACT,STU_EMAIL,STU_ROLLNO,STU_BRANCH) \
      VALUES ('Nancy', '9179785695', 'nancy@gmail.com','MCA225', 'CA')");

conn.commit()
print ("Records inserted successfully")
conn.close()
"""
###Output###
Database Opened successfully
Records inserted successfully
"""

Step 4:Display and Search in SQLite
Here is the complete code of Python that will access and display all the records of registered students from database and you can search record of any particular students by typing his/her name in a textbox.

#import library
#import library for creating GUI
from tkinter import *
import tkinter.ttk as ttk
#import library for handling SQLite database
import sqlite3
#defining function for creating GUI Layout
def DisplayForm():
    #creating window
    display_screen = Tk()
    #setting width and height for window
    display_screen.geometry("800x200")
    #setting title for window
    display_screen.title("krazyprogrammer.com")
    global tree
    global SEARCH
    SEARCH = StringVar()
    #creating frame
    TopViewForm = Frame(display_screen, width=600, bd=1, relief=SOLID)
    TopViewForm.pack(side=TOP, fill=X)
    LeftViewForm = Frame(display_screen, width=600)
    LeftViewForm.pack(side=LEFT, fill=Y)
    MidViewForm = Frame(display_screen, width=600)
    MidViewForm.pack(side=RIGHT)
    lbl_text = Label(TopViewForm, text="SQLite Database Student Records", font=('verdana', 18), width=600,bg="#1C2833",fg="white")
    lbl_text.pack(fill=X)
    lbl_txtsearch = Label(LeftViewForm, text="Search", font=('verdana', 15))
    lbl_txtsearch.pack(side=TOP, anchor=W)

    search = Entry(LeftViewForm, textvariable=SEARCH, font=('verdana', 15), width=10)
    search.pack(side=TOP, padx=10, fill=X)
    btn_search = Button(LeftViewForm, text="Search", command=SearchRecord)
    btn_search.pack(side=TOP, padx=10, pady=10, fill=X)
    btn_search = Button(LeftViewForm, text="View All", command=DisplayData)
    btn_search.pack(side=TOP, padx=10, pady=10, fill=X)

    #setting scrollbar
    scrollbarx = Scrollbar(MidViewForm, orient=HORIZONTAL)
    scrollbary = Scrollbar(MidViewForm, orient=VERTICAL)
    tree = ttk.Treeview(MidViewForm,columns=("Student Id", "Name", "Contact", "Email","Rollno","Branch"),
                        selectmode="extended", height=100, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
    scrollbary.config(command=tree.yview)
    scrollbary.pack(side=RIGHT, fill=Y)
    scrollbarx.config(command=tree.xview)
    scrollbarx.pack(side=BOTTOM, fill=X)
    #setting headings for the columns
    tree.heading('Student Id', text="Student Id", anchor=W)
    tree.heading('Name', text="Name", anchor=W)
    tree.heading('Contact', text="Contact", anchor=W)
    tree.heading('Email', text="Email", anchor=W)
    tree.heading('Rollno', text="Rollno", anchor=W)
    tree.heading('Branch', text="Branch", anchor=W)
    #setting width of the columns
    tree.column('#0', stretch=NO, minwidth=0, width=0)
    tree.column('#1', stretch=NO, minwidth=0, width=100)
    tree.column('#2', stretch=NO, minwidth=0, width=150)
    tree.column('#3', stretch=NO, minwidth=0, width=80)
    tree.column('#4', stretch=NO, minwidth=0, width=120)
    tree.pack()
    DisplayData()
#function to search data
def SearchRecord():
    #checking search text is empty or not
    if SEARCH.get() != "":
        #clearing current display data
        tree.delete(*tree.get_children())
        #open database
        conn = sqlite3.connect('student.db')
        #select query with where clause
        cursor=conn.execute("SELECT * FROM STUD_REGISTRATION WHERE STU_NAME LIKE ?", ('%' + str(SEARCH.get()) + '%',))
        #fetch all matching records
        fetch = cursor.fetchall()
        #loop for displaying all records into GUI
        for data in fetch:
            tree.insert('', 'end', values=(data))
        cursor.close()
        conn.close()
#defining function to access data from SQLite database
def DisplayData():
    #clear current data
    tree.delete(*tree.get_children())
    # open databse
    conn = sqlite3.connect('student.db')
    #select query
    cursor=conn.execute("SELECT * FROM STUD_REGISTRATION")
    #fetch all data from database
    fetch = cursor.fetchall()
    #loop for displaying all data in GUI
    for data in fetch:
        tree.insert('', 'end', values=(data))
    cursor.close()
    conn.close()

#calling function
DisplayForm()
if __name__=='__main__':
#Running Application
 mainloop()

Step 5:Run Program

You just type this above code into your python file or you can copy this code for your personal use. When you will run this code you will get a screen like below 

How to Search data from SQLite in Python

Here as you can see that by default the output screen will display all the students details. If you want to search the record of a student then type the name of student into textbox and click on Search button. For example if you want to search the record of student Nancy then you can type Nancy or Nanc or Nan etc because i am using LIKE operator in SQL query that will return all records that match with given Character or word. For better understanding see the below screenshots. 
How to Search data from SQLite in Python
How to Search data from SQLite in Python

I hope now you can fetch and display data from SQLite and can perform search operation with Python Tkinter.


 Request:-If you found this post helpful then let me know by your comment and share it with your friend. If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. Thanks.😊

Post a Comment

2 Comments

  1. Hi,
    On Step 3, you have STU_ID listed when trying to input 'Nancy' into the database. This breaks the code. If you remove STU_ID, it will run correctly.

    ReplyDelete
    Replies
    1. Yes you are right man... i have fixed it ... thanks for your feedback

      Delete