Python - Search Query In SQLite

In this tutorial we will create a Search Query In SQLite using Python. This code will search a data in the table of SQLite database when user submit the required information. The code use tkinter module to design a layout and call a specific functions. A function will automatically call when you the designated entry widget then it will run the SQLite SELECT query with a condition of LIKE in WHERE clause. We will be using Python programming language because it is widely used as an advance-level programming language for a general technique to the developer. Beginners find Python a clean syntax and indentation structure based, and it is easy to learn because of its less semi colon problem.

Getting started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Installing SQLite Browser

After you installed Python, we will now then install the SQLite, here's the link for the DB Browser for SQLite http://sqlitebrowser.org/.

Importing Modules

After setting up the installation and the database, run the IDLE and click file and then new file. After that a new window will appear containing a black file this will be the text editor for the python. Then copy code that I provided below and paste it inside the IDLE text editor.
  1. from tkinter import *
  2. import sqlite3
  3. import tkinter.ttk as ttk

Setting up the Main Frame

After importing the modules, we will now then create the main frame for the application. To do that just copy the code below and paste it inside the IDLE text editor.
  1. root = Tk()
  2. root.title("Python - Search Query In SQLite")
  3. width = 600
  4. height = 400
  5. screen_width = root.winfo_screenwidth()
  6. screen_height = root.winfo_screenheight()
  7. x = (screen_width/2) - (width/2)
  8. y = (screen_height/2) - (height/2)
  9. root.geometry("%dx%d+%d+%d" % (width, height, x, y))
  10. root.resizable(0, 0)

Creating the Database Connection

Then after setting up the design we will now create the database function. To do that just simply copy the code below and paste it inside the IDLE text editor.
  1. def Database():
  2.     conn = sqlite3.connect("db_member.db")
  3.     cursor = conn.cursor()
  4.     cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER NOT NULL PRIMARY KEY  AUTOINCREMENT, firstname TEXT, lastname TEXT, address TEXT, age TEXT)")
  5.     cursor.execute("SELECT * FROM `member`")
  6.     if cursor.fetchone() is None:
  7.         cursor.execute("INSERT INTO `member` (firstname, lastname, address, age) VALUES('John', 'Smith', 'Pallet Town', '20')")
  8.         cursor.execute("INSERT INTO `member` (firstname, lastname, address, age) VALUES('Claire', 'Temple', 'Racoon City', '19')")
  9.         conn.commit()
  10.        
  11.     cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  12.     fetch = cursor.fetchall()
  13.     for data in fetch:
  14.         tree.insert('', 'end', values=(data))
  15.     cursor.close()
  16.     conn.close()

Assigning Variables

This is where the we will assign the variables. This code will assign each of the variables to be use later in the application.
  1. #=====================================VARIABLES============================================
  2. SEARCH = StringVar()

Designing the Layout

After creating the Main Frame we will now add some layout to the application. Just kindly copy the code below and paste it inside the IDLE text editor.
  1. #=====================================FRAME================================================
  2. Top = Frame(root, width=500, bd=1, relief=SOLID)
  3. Top.pack(side=TOP)
  4. MidFrame = Frame(root, width=500)
  5. MidFrame.pack(side=TOP)
  6. LeftForm= Frame(MidFrame, width=100)
  7. LeftForm.pack(side=LEFT)
  8. RightForm= Frame(MidFrame, width=500)
  9. RightForm.pack(side=RIGHT)
  10.  
  11.  
  12. #=====================================LABEL WIDGET=========================================
  13. lbl_title = Label(Top, width=500, font=('arial', 18), text="Python - Search Query In SQLite")
  14. lbl_title.pack(side=TOP, fill=X)
  15. lbl_search = Label(LeftForm, font=('arial', 15), text="Search here...")
  16. lbl_search.pack(side=TOP)
  17.  
  18. #=====================================ENTRY WIDGET=========================================
  19. search = Entry(LeftForm, textvariable=SEARCH)
  20. search.pack(side=TOP, pady=10)
  21.  
  22. #=====================================BUTTON WIDGET========================================
  23. btn_search = Button(LeftForm, text="Search", bg="#006dcc", command=Search)
  24. btn_search.pack(side=LEFT)
  25. btn_reset = Button(LeftForm, text="Reset", command=Reset)
  26. btn_reset.pack(side=LEFT)
  27. #=====================================Table WIDGET=========================================
  28. scrollbarx = Scrollbar(RightForm, orient=HORIZONTAL)
  29. scrollbary = Scrollbar(RightForm, orient=VERTICAL)
  30. tree = ttk.Treeview(RightForm, columns=("MemberID", "Firstname", "Lastname", "Address", "Age"), selectmode="extended", height=400, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
  31. scrollbary.config(command=tree.yview)
  32. scrollbary.pack(side=RIGHT, fill=Y)
  33. scrollbarx.config(command=tree.xview)
  34. scrollbarx.pack(side=BOTTOM, fill=X)
  35. tree.heading('MemberID', text="MemberID",anchor=W)
  36. tree.heading('Firstname', text="Firstname",anchor=W)
  37. tree.heading('Lastname', text="Lastname",anchor=W)
  38. tree.heading('Address', text="Address",anchor=W)
  39. tree.heading('Age', text="Age",anchor=W)
  40. tree.column('#0', stretch=NO, minwidth=0, width=0)
  41. tree.column('#1', stretch=NO, minwidth=0, width=0)
  42. tree.column('#2', stretch=NO, minwidth=0, width=80)
  43. tree.column('#3', stretch=NO, minwidth=0, width=120)
  44. tree.column('#4', stretch=NO, minwidth=0, width=170)
  45. tree.column('#5', stretch=NO, minwidth=0, width=80)
  46. tree.pack()

Creating the Main Function

This is where the code that contains the main funcitions. This code will search a SQLite data when the button is clicked. To do that just copy and write these blocks of code.
  1. #=====================================METHODS==============================================
  2. def Search():
  3.     if SEARCH.get() != "":
  4.         tree.delete(*tree.get_children())
  5.         conn = sqlite3.connect("db_member.db")
  6.         cursor = conn.cursor()
  7.         cursor.execute("SELECT * FROM `member` WHERE `firstname` LIKE ? OR `lastname` LIKE ?", ('%'+str(SEARCH.get())+'%', '%'+str(SEARCH.get())+'%'))
  8.         fetch = cursor.fetchall()
  9.         for data in fetch:
  10.             tree.insert('', 'end', values=(data))
  11.         cursor.close()
  12.         conn.close()
  13. def Reset():
  14.     conn = sqlite3.connect("db_member.db")
  15.     cursor = conn.cursor()
  16.     tree.delete(*tree.get_children())
  17.     cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  18.     fetch = cursor.fetchall()
  19.     for data in fetch:
  20.         tree.insert('', 'end', values=(data))
  21.     cursor.close()
  22.     conn.close()

Initializing the Application

After finishing the function save the application as index.py. This function will run the code and check if the main application is initialized properly. To do that copy the code below and paste it inside the IDLE text editor.
  1. #=====================================INITIALIZATION=======================================
  2. if __name__ == '__main__':
  3.     Database()
  4.     root.mainloop()
There you have it we just created a Search Query In SQLite Using Python. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!

Add new comment