Python: Simple CRUD Application Using SQLite - Part 1

Submitted by: 
Language: 
Visitors have accessed this post 870 times.

In this tutorial we will create a simple CRUD ( Create, Read ) Application using Python/SQLite. Python is a computer programming language that lets work faster and convenient because of its user - friendly environment. Python supports packages and modules, which encourage a developer to program in a modularity and reusable way. By the way this tutorial is consist of two parts, for now we will tackle only about create and read on Python with SQLite database. So let's now do the coding

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

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: Simple CRUD Applition")
  3. screen_width = root.winfo_screenwidth()
  4. screen_height = root.winfo_screenheight()
  5. width = 900
  6. height = 500
  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)

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. #==================================VARIABLES==========================================
  2. FIRSTNAME = StringVar()
  3. LASTNAME = StringVar()
  4. GENDER = StringVar()
  5. ADDRESS = StringVar()
  6. USERNAME = StringVar()
  7. PASSWORD = StringVar()
  8.  
  9. #==================================FRAME==============================================
  10. Top = Frame(root, width=900, height=50, bd=8, relief="raise")
  11. Top.pack(side=TOP)
  12. Left = Frame(root, width=300, height=500, bd=8, relief="raise")
  13. Left.pack(side=LEFT)
  14. Right = Frame(root, width=600, height=500, bd=8, relief="raise")
  15. Right.pack(side=RIGHT)
  16. Forms = Frame(Left, width=300, height=450)
  17. Forms.pack(side=TOP)
  18. Buttons = Frame(Left, width=300, height=100, bd=8, relief="raise")
  19. Buttons.pack(side=BOTTOM)
  20. RadioGroup = Frame(Forms)
  21. Male = Radiobutton(RadioGroup, text="Male", variable=GENDER, value="Male", font=('arial', 16)).pack(side=LEFT)
  22. Female = Radiobutton(RadioGroup, text="Female", variable=GENDER, value="Female", font=('arial', 16)).pack(side=LEFT)
  23.  
  24. #==================================LABEL WIDGET=======================================
  25. txt_title = Label(Top, width=900, font=('arial', 24), text = "Python: Simple CRUD Application")
  26. txt_title.pack()
  27. txt_firstname = Label(Forms, text="Firstname:", font=('arial', 16), bd=15)
  28. txt_firstname.grid(row=0, stick="e")
  29. txt_lastname = Label(Forms, text="Lastname:", font=('arial', 16), bd=15)
  30. txt_lastname.grid(row=1, stick="e")
  31. txt_gender = Label(Forms, text="Gender:", font=('arial', 16), bd=15)
  32. txt_gender.grid(row=2, stick="e")
  33. txt_address = Label(Forms, text="Address:", font=('arial', 16), bd=15)
  34. txt_address.grid(row=3, stick="e")
  35. txt_username = Label(Forms, text="Username:", font=('arial', 16), bd=15)
  36. txt_username.grid(row=4, stick="e")
  37. txt_password = Label(Forms, text="Password:", font=('arial', 16), bd=15)
  38. txt_password.grid(row=5, stick="e")
  39. txt_result = Label(Buttons)
  40. txt_result.pack(side=TOP)
  41.  
  42. #==================================ENTRY WIDGET=======================================
  43. firstname = Entry(Forms, textvariable=FIRSTNAME, width=30)
  44. firstname.grid(row=0, column=1)
  45. lastname = Entry(Forms, textvariable=LASTNAME, width=30)
  46. lastname.grid(row=1, column=1)
  47. RadioGroup.grid(row=2, column=1)
  48. address = Entry(Forms, textvariable=ADDRESS, width=30)
  49. address.grid(row=3, column=1)
  50. username = Entry(Forms, textvariable=USERNAME, width=30)
  51. username.grid(row=4, column=1)
  52. password = Entry(Forms, textvariable=PASSWORD, show="*", width=30)
  53. password.grid(row=5, column=1)
  54.  
  55. #==================================BUTTONS WIDGET=====================================
  56. btn_create = Button(Buttons, width=10, text="Create", command=Create)
  57. btn_create.pack(side=LEFT)
  58. btn_read = Button(Buttons, width=10, text="Read", command=Read )
  59. btn_read.pack(side=LEFT)
  60. btn_update = Button(Buttons, width=10, text="Update", state=DISABLED)
  61. btn_update.pack(side=LEFT)
  62. btn_delete = Button(Buttons, width=10, text="Delete", state=DISABLED)
  63. btn_delete.pack(side=LEFT)
  64. btn_exit = Button(Buttons, width=10, text="Exit", command=Exit)
  65. btn_exit.pack(side=LEFT)
  66.  
  67. #==================================LIST WIDGET========================================
  68. scrollbary = Scrollbar(Right, orient=VERTICAL)
  69. scrollbarx = Scrollbar(Right, orient=HORIZONTAL)
  70. tree = ttk.Treeview(Right, columns=("Firstname", "Lastname", "Gender", "Address", "Username", "Password"), selectmode="extended", height=500, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
  71. scrollbary.config(command=tree.yview)
  72. scrollbary.pack(side=RIGHT, fill=Y)
  73. scrollbarx.config(command=tree.xview)
  74. scrollbarx.pack(side=BOTTOM, fill=X)
  75. tree.heading('Firstname', text="Firstname", anchor=W)
  76. tree.heading('Lastname', text="Lastname", anchor=W)
  77. tree.heading('Gender', text="Gender", anchor=W)
  78. tree.heading('Address', text="Address", anchor=W)
  79. tree.heading('Username', text="Username", anchor=W)
  80. tree.heading('Password', text="Password", anchor=W)
  81. tree.column('#0', stretch=NO, minwidth=0, width=0)
  82. tree.column('#1', stretch=NO, minwidth=0, width=80)
  83. tree.column('#2', stretch=NO, minwidth=0, width=120)
  84. tree.column('#3', stretch=NO, minwidth=0, width=80)
  85. tree.column('#4', stretch=NO, minwidth=0, width=150)
  86. tree.column('#5', stretch=NO, minwidth=0, width=120)
  87. tree.column('#6', stretch=NO, minwidth=0, width=120)
  88. tree.pack()

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. #==================================METHODS============================================
  2. def Database():
  3. global conn, cursor
  4. conn = sqlite3.connect('pythontut.db')
  5. cursor = conn.cursor()
  6. cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, firstname TEXT, lastname TEXT, gender TEXT, address TEXT, username TEXT, password TEXT)")

Creating the Create Function
This where the code will send the data to database when button create is clicked. Copy the code below and paste it inside the IDLE text editor

  1. def Create():
  2. if FIRSTNAME.get() == "" or LASTNAME.get() == "" or GENDER.get() == "" or ADDRESS.get() == "" or USERNAME.get() == "" or PASSWORD.get() == "":
  3. txt_result.config(text="Please complete the required field!", fg="red")
  4. else:
  5. Database()
  6. cursor.execute("INSERT INTO `member` (firstname, lastname, gender, address, username, password) VALUES(?, ?, ?, ?, ?, ?)", (str(FIRSTNAME.get()), str(LASTNAME.get()), str(GENDER.get()), str(ADDRESS.get()), str(USERNAME.get()), str(PASSWORD.get())))
  7. conn.commit()
  8. FIRSTNAME.set("")
  9. LASTNAME.set("")
  10. GENDER.set("")
  11. ADDRESS.set("")
  12. USERNAME.set("")
  13. PASSWORD.set("")
  14. cursor.close()
  15. conn.close()
  16. txt_result.config(text="Created a data!", fg="green")

Creating the Read Function
This where the code will retrieve the data from the database and display it in the Python widget called Treeview. Just simply copy the code below and paste it inside the IDLE text editor

  1. def Read():
  2. tree.delete(*tree.get_children())
  3. Database()
  4. cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  5. fetch = cursor.fetchall()
  6. for data in fetch:
  7. tree.insert('', 'end', values=(data[1], data[2], data[3], data[4], data[5], data[6]))
  8. cursor.close()
  9. conn.close()
  10. txt_result.config(text="Successfully read the data from database", fg="black")

Creating the Exit Function
This where the code will destroy the frame and force to close the application when button exit is clicked. To do that just simple copy the code below and paste it inside the IDLE text editor

  1. def Exit():
  2. result = tkMessageBox.askquestion('Python: Simple CRUD Applition', 'Are you sure you want to exit?', icon="warning")
  3. if result == 'yes':
  4. root.destroy()
  5. exit()

Initializing the Application
After finishing the function save the application as 'index.py'. This function will run the code and check if the main is initialize properly. To do that copy the code below and paste it inside the IDLE text editor.

  1. #==================================INITIALIZATION=====================================
  2. if __name__ == '__main__':
  3. root.mainloop()

There you have it we create a simple CRUD ( Create, Read ) Application using Python and SQLite. For the next part of the tutorial we will tackle on how to update and delete the data so just stay tuned to this site. I hope that this simple tutorial help you improve to your programming carrier. Enjoy Coding!!


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3>
  • You may insert videos with [video:URL]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.