Python - Sorting Data In SQLite3

In this tutorial we will create a Sorting Data In SQLite3 using Python. This code will sort all the data in the SQLite database in TreeView when user click the sorting button. The code use tkinter module to create a layout and widgets that can call python functions. When a function is called it will immediately sort the data whether ASCENDING or DESCENDING in TreeView by SQLite SELECT query and adding ORDER BY parameter. We will be using Python because it has a design philosophy which emphasizes code readability. That's why python is very easy to use especially for beginners who just started programming. It is very easy to learn the syntax emphasizes readability and it can reduces time consuming in developing..

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 tkinter.ttk as ttk
  3. import tkinter.messagebox as tkMessageBox
  4. import connection

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 - Sorting Data In SQLite3")
  3. screen_width = root.winfo_screenwidth()
  4. screen_height = root.winfo_screenheight()
  5. width = 700
  6. height = 300
  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, then save it as connection.py.
  1. import sqlite3
  2.  
  3. def Database():
  4. global conn, cursor
  5. conn = sqlite3.connect('db_member.db')
  6. cursor = conn.cursor()
  7. cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, firstname TEXT, lastname TEXT, address TEXT)")

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=700, height=50, bd=8, relief="raise")
  3. Top.pack(side=TOP)
  4. Button_Group=Frame(root, width=700, height=50)
  5. Button_Group.pack(side=TOP)
  6. Buttons = Frame(Button_Group, width=300, height=50)
  7. Buttons.pack(side=LEFT)
  8. Buttons1 = Frame(Button_Group, width=400, height=50)
  9. Buttons1.pack(side=RIGHT)
  10. Body = Frame(root, width=700, height=300, bd=8, relief="raise")
  11. Body.pack(side=BOTTOM)
  12.  
  13.  
  14. #==================================LABEL WIDGET=======================================
  15. txt_title = Label(Top, width=300, font=('arial', 24), text = "Python - Sorting Data In SQLite3")
  16. txt_title.pack()
  17.  
  18. #==================================BUTTONS WIDGET=====================================
  19. btn_asc = Button(Buttons, width=15, text="ASCENDING", command=ascData)
  20. btn_asc.pack(side=LEFT)
  21. btn_desc = Button(Buttons, width=15, text="DESCENDING", command=descData)
  22. btn_desc.pack(side=LEFT)
  23.  
  24.  
  25. #==================================LIST WIDGET========================================
  26. scrollbary = Scrollbar(Body, orient=VERTICAL)
  27. scrollbarx = Scrollbar(Body, orient=HORIZONTAL)
  28. tree = ttk.Treeview(Body, columns=("Firstname", "Lastname", "Address"), selectmode="extended", height=300, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
  29. scrollbary.config(command=tree.yview)
  30. scrollbary.pack(side=RIGHT, fill=Y)
  31. scrollbarx.config(command=tree.xview)
  32. scrollbarx.pack(side=BOTTOM, fill=X)
  33. tree.heading('Firstname', text="Firstname", anchor=W)
  34. tree.heading('Lastname', text="Lastname", anchor=W)
  35. tree.heading('Address', text="Address", anchor=W)
  36. tree.column('#0', stretch=NO, minwidth=0, width=0)
  37. tree.column('#1', stretch=NO, minwidth=0, width=200)
  38. tree.column('#2', stretch=NO, minwidth=0, width=200)
  39. tree.column('#3', stretch=NO, minwidth=0, width=200)
  40. tree.pack()

Creating the Main Function

This is where the code that contains the main funcitions. This code will sort all the SQLite data in TreeView when the button is clicked. To do that just copy and write these blocks of code.
  1. #==================================METHODS============================================
  2. def displayData():
  3. tree.delete(*tree.get_children())
  4. connection.Database()
  5. connection.cursor.execute("SELECT * FROM `member`")
  6. fetch = connection.cursor.fetchall()
  7. for data in fetch:
  8. tree.insert('', 'end', values=(data[1], data[2], data[3]))
  9. connection.cursor.close()
  10. connection.conn.close()
  11.  
  12. def ascData():
  13. tree.delete(*tree.get_children())
  14. connection.Database()
  15. connection.cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  16. fetch = connection.cursor.fetchall()
  17. for data in fetch:
  18. tree.insert('', 'end', values=(data[1], data[2], data[3]))
  19. connection.cursor.close()
  20. connection.conn.close()
  21.  
  22. def descData():
  23. tree.delete(*tree.get_children())
  24. connection.Database()
  25. connection.cursor.execute("SELECT * FROM `member` ORDER BY `lastname` DESC")
  26. fetch = connection.cursor.fetchall()
  27. for data in fetch:
  28. tree.insert('', 'end', values=(data[1], data[2], data[3]))
  29. connection.cursor.close()
  30. connection.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.  
  3. if __name__ == '__main__':
  4. displayData()
  5. root.mainloop()
There you have it we just created a Sorting Data In SQLite3 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