Python SQLite3 Tutorial | Registration with SQLite in Python Tkinter

Hello friends how are you, Today in this post "Python SQLite3 Tutorial | Registration with SQLite in Python" i am going to teach you how you can insert data into SQLite database using Tkinter GUI interface. If you are a Computer Science students and want to create GUI based application using Database then this post will help you definitely.

Now i am going to explain everything step by step
Step 1:Connection with Database

To create a connection with SQLite first we have to import a module sqlite3 in our code then we can create a connection object to connect. A predefined function connect() of module sqlite3 is used to create a connection object.  Following is the code to connect with SQLite database. Create any python file and type the following code

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

Here we can type any  name for database for example i have created a student database . After typing the database name don't forget to add .db because it is the extension of database file. when you will run this code a database file with name student will be created inside the current directory but you can change your file path if needed. when you will run this code you will get a message like Database created successfully. Below is the screenshot of project folder.

How to use SQLite in Python

In the above screenshot you can see that a database file with name student is created.

Step 2:Create Table

After creating database we need to create a table inside database. Here i am going to create a STUDENT REGISTRATION table with following fields[STUD_ID,STU_NAME,STU_CONTACT,STU_EMAIL,STU_ROLLNO,STU_BRANCH]. Here is the complete code to create this table in the 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. If you want to see your table in SQLite then you can use DB Browser.

Step 3[Optional]:Insert data into table

Now i am going to insert data into table. By using SQL query we can insert data into tables. 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_ID,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[Optional]:Select data from table

Now its time to see the data stored in Database table. Following is the program to fetch data from table 

import sqlite3

conn = sqlite3.connect('student.db')
print ("Database opened successfully")

cursor = conn.execute("SELECT * from STUD_REGISTRATION")
print("ID\tNAME\tCONTACT\t\tEMAIL\t\t\tROLLLNO\tBRANCH")
for row in cursor:
   print ("{}\t{}\t{}\t{}\t{}\t{}".format(row[0],row[1],row[2],row[3],row[4],row[5]))
conn.close()

When you will execute this program then  you will get output like below screenshot

Python SQLite3 Tutorial | Registration with SQLite in Python Tkinter

Here you can verify that these are the records which are inserted using query.

Step 5: Create GUI Registration Form :Now i am going insert data into SQLite database using Graphical User Interface. Here is the complete code for GUI Registration form.

#import needed library
from tkinter import *
from  tkinter import  ttk
import sqlite3
#open databse
conn = sqlite3.connect('student.db')
#defining register function
def register():
    #getting form data
    name1=name.get()
    con1=contact.get()
    email1=email.get()
    rol1=rollno.get()
    branch1=branch.get()
    #applying empty validation
    if name1=='' or con1==''or email1=='' or rol1==''or branch1=='':
        message.set("fill the empty field!!!")
    else:
        #SQLite code to insert data
        conn.execute('INSERT INTO STUD_REGISTRATION (STU_NAME,STU_CONTACT,STU_EMAIL,STU_ROLLNO,STU_BRANCH) \
              VALUES (?,?,?,?,?)',(name1,con1,email1,rol1,branch1));
        conn.commit()
        message.set("Stored successfully")
        #print("Records inserted successfully")
        conn.close()

#defining Registrationform function
def Registrationform():
    global reg_screen
    reg_screen = Tk()
    #Setting title of screen
    reg_screen.title("krazyprogrammers.com")
    #setting height and width of screen
    reg_screen.geometry("550x400")
    reg_screen["bg"]="#1C2833"
    #declaring variable
    global  message;
    global name
    global contact
    global email
    global rollno
    global branch
    name = StringVar()
    contact = StringVar()
    email=StringVar()
    rollno=StringVar()
    branch=StringVar()
    message=StringVar()
    #Creating layout of Registration form
    Label(reg_screen,width="300", text="Please enter details below",bg="#0E6655",fg="white",font=("Arial",12,"bold")).pack()
    #name Label
    Label(reg_screen, text="Name * ",bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=20,y=40)
    #name textbox
    Entry(reg_screen, textvariable=name,bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=90,y=42)
    #contact Label
    Label(reg_screen, text="Contact * ",bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=20,y=80)
    #contact textbox
    Entry(reg_screen, textvariable=contact,bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=90,y=82)
    # email Label
    Label(reg_screen, text="Email * ",bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=20, y=120)
    # email textbox
    Entry(reg_screen, textvariable=email,bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=90, y=122)

    # rollno Label
    Label(reg_screen, text="Rollno * ",bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=20, y=160)
    Entry(reg_screen, textvariable=rollno,bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=90, y=162)

    # branch Label
    Label(reg_screen, text="branch * ",bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=20, y=200)
    # branch combobox
    monthchoosen = ttk.Combobox(reg_screen, width=27, textvariable=branch,background="#1C2833")
    monthchoosen['values'] = (' COMPUTER SCIENCE',
                              ' INFORMATION TECHNOLOGY',
                              ' ELECTRONICS & COMMUNICATION',
                              ' ELECTRICAL ENGINEERING',
                              ' MECHANICAL ENGINEERING',
                              ' CIVIL ENGINEERING',
                              ' COMPUTER APPLICATION',)
    monthchoosen.current()
    monthchoosen.place(x=90,y=202)
    #Label for displaying login status[success/failed]
    Label(reg_screen, text="",textvariable=message,bg="#1C2833",fg="white",font=("Arial",12,"bold")).place(x=95,y=234)
    #Login button
    Button(reg_screen, text="Register", width=10, height=1, bg="#0E6655",command=register,fg="white",font=("Arial",12,"bold")).place(x=105,y=300)
    reg_screen.mainloop()
#calling function Registrationform
Registrationform()
 
You just type this 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
Python SQLite3 Tutorial | Registration with SQLite in Python Tkinter

Now just fill the above registration details and click on Register button to save this data into SQLite database. for better understanding see the below screenshot
Python SQLite3 Tutorial | Registration with SQLite in Python Tkinter

Now again run the select query, and this time you will get one more record is inserted into SQLite database.
Python SQLite3 Tutorial | Registration with SQLite in Python Tkinter

I hope now you can do Registration using SQLite 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

0 Comments