Unit-3: Python Interaction with SQLite
3.1 Importing sqlite3 Module
SQLite is a lightweight, serverless database that comes built-in with Python. The sqlite3
module allows Python programs to interact with SQLite databases.
Basic Import and Setup
import sqlite3
# Connect to database (creates file if doesn't exist)
conn = [Link]('[Link]')
cursor = [Link]()
3.1.1 connect() and execute() Methods
connect() Method
● Creates a connection to SQLite database
● If database doesn't exist, it creates a new one
● Returns a Connection object
# Connect to database file
conn = [Link]('[Link]')
# Connect to in-memory database (temporary)
conn = [Link](':memory:')
# Get cursor object to execute SQL commands
cursor = [Link]()
execute() Method
● Executes a single SQL statement
● Returns a cursor object
● Used for CREATE, INSERT, UPDATE, DELETE, SELECT operations
# Create table
[Link]('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
grade TEXT)''')
# Insert data
[Link]("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("Alice", 20, "A"))
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 1
3.1.2 Single Row and Multi-row Fetch
fetchone()
● Retrieves only one row from the result set
● Returns a tuple or None if no data found
[Link]("SELECT * FROM students WHERE id = ?", (1,))
row = [Link]()
if row:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}, Grade: {row[3]}")
else:
print("No student found")
fetchall()
● Retrieves all remaining rows from the result set
● Returns a list of tuples
[Link]("SELECT * FROM students")
rows = [Link]()
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}, Grade: {row[3]}")
fetchmany(size)
● Retrieves specified number of rows
● Useful for large datasets
[Link]("SELECT * FROM students")
rows = [Link](5) # Get first 5 rows
for row in rows:
print(row)
3.1.3 Select, Insert, Update, Delete using execute() Method
SELECT Operation
# Select all records
[Link]("SELECT * FROM students")
all_students = [Link]()
# Select with condition
[Link]("SELECT name, grade FROM students WHERE age > ?", (18,))
adult_students = [Link]()
# Select with ORDER BY
[Link]("SELECT * FROM students ORDER BY name ASC")
sorted_students = [Link]()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 2
INSERT Operation
# Insert single record
[Link]("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("Bob", 19, "B"))
# Insert multiple records
students_data = [
("Charlie", 21, "A"),
("David", 18, "C"),
("Eve", 20, "B")
]
[Link]("INSERT INTO students (name, age, grade) VALUES (?, ?,
?)", students_data)
UPDATE Operation
# Update single record
[Link]("UPDATE students SET grade = ? WHERE id = ?", ("A+", 1))
# Update multiple records
[Link]("UPDATE students SET age = age + 1 WHERE grade = ?", ("A",))
DELETE Operation
# Delete single record
[Link]("DELETE FROM students WHERE id = ?", (1,))
# Delete multiple records
[Link]("DELETE FROM students WHERE age < ?", (18,))
# Delete all records
[Link]("DELETE FROM students")
3.1.4 commit() Method
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 3
The commit() method saves changes to the database permanently. Without commit, changes
are temporary.
import sqlite3
conn = [Link]('[Link]')
cursor = [Link]()
try:
# Create table
[Link]('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# Insert data
[Link]("INSERT INTO students (name, age) VALUES (?, ?)",
("John", 22))
# Commit changes - IMPORTANT!
[Link]()
print("Data inserted successfully")
except [Link] as e:
print(f"Error: {e}")
[Link]() # Undo changes if error occurs
finally:
[Link]()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 4
3.2 SQLite Dump
Database dumping creates backup copies of database structure and/or data in SQL format.
3.2.1 Dump Specific Table into File, Dump Only Table Structure
Dump Specific Table
import sqlite3
def dump_table_to_file(db_name, table_name, output_file):
conn = [Link](db_name)
with open(output_file, 'w') as f:
# Dump table structure and data
for line in [Link]():
if table_name in line:
[Link](line + '\n')
[Link]()
# Usage
dump_table_to_file('[Link]', 'students', 'students_dump.sql')
Dump Only Table Structure
def dump_table_structure(db_name, table_name, output_file):
conn = [Link](db_name)
cursor = [Link]()
# Get CREATE TABLE statement
[Link]("SELECT sql FROM sqlite_master WHERE type='table' AND
name=?",
(table_name,))
create_sql = [Link]()[0]
with open(output_file, 'w') as f:
[Link](create_sql + ';\n')
[Link]()
# Usage
dump_table_structure('[Link]', 'students', 'students_structure.sql')
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 5
3.2.2 Dump Entire Database into File
def dump_entire_database(db_name, output_file):
conn = [Link](db_name)
with open(output_file, 'w') as f:
for line in [Link]():
[Link](line + '\n')
[Link]()
print(f"Database dumped to {output_file}")
# Usage
dump_entire_database('[Link]', 'full_backup.sql')
3.2.3 Dump Data of One or More Tables into a File
def dump_multiple_tables(db_name, table_names, output_file):
conn = [Link](db_name)
with open(output_file, 'w') as f:
for line in [Link]():
for table_name in table_names:
if table_name in line:
[Link](line + '\n')
break
[Link]()
# Usage
dump_multiple_tables('[Link]', ['students', 'teachers'],
'school_data.sql')
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 6
3.3 CSV Files Handling
3.3.1 Import a CSV file into a Table
import csv
import sqlite3
def import_csv_to_table(csv_file, db_name, table_name):
conn = [Link](db_name)
cursor = [Link]()
with open(csv_file, 'r') as file:
csv_reader = [Link](file)
headers = next(csv_reader) # Read header row
# Create table dynamically
columns = ', '.join([f"{header} TEXT" for header in headers])
[Link](f"CREATE TABLE IF NOT EXISTS {table_name}
({columns})")
# Insert data
placeholders = ', '.join(['?' for _ in headers])
for row in csv_reader:
[Link](f"INSERT INTO {table_name} VALUES
({placeholders})", row)
[Link]()
[Link]()
print(f"CSV data imported to {table_name}")
# Usage
import_csv_to_table('[Link]', '[Link]', 'students')
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 7
3.3.2 Export a CSV file from Table
def export_table_to_csv(db_name, table_name, csv_file):
conn = [Link](db_name)
cursor = [Link]()
# Get column names
[Link](f"PRAGMA table_info({table_name})")
columns = [column[1] for column in [Link]()]
# Get data
[Link](f"SELECT * FROM {table_name}")
data = [Link]()
with open(csv_file, 'w', newline='') as file:
csv_writer = [Link](file)
csv_writer.writerow(columns) # Write headers
csv_writer.writerows(data) # Write data
[Link]()
print(f"Table {table_name} exported to {csv_file}")
# Usage
export_table_to_csv('[Link]', 'students', 'exported_students.csv')
3.4 Developing Python GUI with Tkinter
3.4.1 Introduction to GUI Libraries of Python & Importing Tkinter Libraries
What is a GUI?
GUI (Graphical User Interface) is a way to interact with a program using visual components like:
Buttons, Text boxes, Labels, Windows,Sliders
Instead of typing commands, users can click or drag, making the application user-friendly.
Python GUI Libraries
Python offers many libraries to create GUI applications. Some popular ones include:
Library Description
Tkinter Built-in with Python, simplest for beginners.
PyQt / PySide Feature-rich, professional apps, based on Qt framework.
Kivy For mobile & multitouch apps, modern UIs.
wxPython Native look across platforms, wrapper around C++ wxWidgets.
PyGTK Works with GNOME desktop apps.
Among these, Tkinter is the most widely used in education and simple desktop apps.
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 8
What is Tkinter?
Tkinter is Python’s standard GUI package. It is a wrapper around a toolkit called Tcl/Tk.
Since it’s built into Python, you don’t need to install it separately.
It is lightweight and easy for building small applications like:
Form input apps, Calculator, Attendance GUI, File viewer, Mini games
How to Import Tkinter?
Tkinter is available in two ways depending on Python version:
Python 3.x:
import tkinter as tk
Or you can import everything directly:
from tkinter import *
Python 2.x (not recommended anymore):
import Tkinter
Example:
import tkinter as tk
from tkinter import ttk # Themed widgets
from tkinter import messagebox
from tkinter import filedialog
# Create main window
root = [Link]()
[Link]("My GUI Application")
[Link]("400x300")
[Link]()
3.4.2 Geometry Management
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 9
Tkinter provides three geometry managers to control widget placement:
[Link] place(), grid(), pack()
place() Method
● Positions widgets using absolute or relative coordinates
● Most flexible but requires manual positioning
import tkinter as tk
root = [Link]()
[Link]("400x300")
# Absolute positioning
label1 = [Link](root, text="Absolute Position", bg="red")
[Link](x=50, y=50)
# Relative positioning
label2 = [Link](root, text="Relative Position", bg="blue")
[Link](relx=0.5, rely=0.5, anchor="center")
[Link]()
grid() Method
● Organizes widgets in rows and columns
● Best for structured layouts
import tkinter as tk
root = [Link]()
[Link]("Grid Layout")
# Create widgets in grid
[Link](root, text="Name:").grid(row=0, column=0, sticky="e", padx=5,
pady=5)
[Link](root).grid(row=0, column=1, padx=5, pady=5)
[Link](root, text="Age:").grid(row=1, column=0, sticky="e", padx=5,
pady=5)
[Link](root).grid(row=1, column=1, padx=5, pady=5)
[Link](root, text="Submit").grid(row=2, column=0, columnspan=2, pady=10)
[Link]()
pack() Method
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 10
● Stacks widgets vertically or horizontally
● Simple but limited control
import tkinter as tk
root = [Link]()
[Link]("Pack Layout")
# Pack widgets
[Link](root, text="Header", bg="lightblue").pack(side="top", fill="x")
[Link](root, text="Left Panel", bg="lightgreen").pack(side="left",
fill="y")
[Link](root, text="Right Panel", bg="lightyellow").pack(side="right",
fill="y")
[Link](root, text="Footer", bg="lightcoral").pack(side="bottom",
fill="x")
[Link]()
[Link] Set the Dimensions of the Tkinter Window
import tkinter as tk
root = [Link]()
# Set window size
[Link]("800x600") # width x height
# Set window position
[Link]("800x600+100+50") # width x height + x_offset + y_offset
# Set minimum and maximum size
[Link](400, 300)
[Link](1200, 800)
# Make window resizable or not
[Link](True, True) # width, height
[Link]()
[Link] Handling Resize
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 11
import tkinter as tk
def on_resize(event):
print(f"Window resized to: {[Link]}x{[Link]}")
root = [Link]()
[Link]("400x300")
# Bind resize event
[Link]('<Configure>', on_resize)
# Create responsive layout
frame = [Link](root, bg="lightblue")
[Link](fill="both", expand=True)
label = [Link](frame, text="Resizable Content", bg="white")
[Link](expand=True)
[Link]()
3.5 Tkinter Widgets
Common Tkinter Widgets
Label Widget
import tkinter as tk
root = [Link]()
# Basic label
label1 = [Link](root, text="Hello, World!")
[Link]()
# Styled label
label2 = [Link](root, text="Styled Label",
bg="blue", fg="white",
font=("Arial", 16, "bold"))
[Link]()
[Link]()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 12
Button Widget
import tkinter as tk
def button_click():
print("Button clicked!")
root = [Link]()
# Basic button
button1 = [Link](root, text="Click Me", command=button_click)
[Link]()
# Styled button
button2 = [Link](root, text="Styled Button",
bg="green", fg="white",width=20, height=2)
[Link]()
[Link]()
Entry Widget
import tkinter as tk
def get_text():
text = [Link]()
print(f"Entered text: {text}")
root = [Link]()
entry = [Link](root, width=30)
[Link]()
button = [Link](root, text="Get Text", command=get_text)
[Link]()
[Link]()
Text Widget
import tkinter as tk
root = [Link]()
# Multi-line text widget
text_widget = [Link](root, width=40, height=10)
text_widget.pack()
# Insert text
text_widget.insert("1.0", "This is a text widget\nYou can type here")
[Link]()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 13
Listbox Widget
import tkinter as tk
def on_select(event):
selection = [Link]()
if selection:
item = [Link](selection[0])
print(f"Selected: {item}")
root = [Link]()
listbox = [Link](root)
[Link]()
# Add items
items = ["Apple", "Banana", "Orange", "Grape"]
for item in items:
[Link]([Link], item)
# Bind selection event
[Link]('<<ListboxSelect>>', on_select)
[Link]()
Frame Widget
import tkinter as tk
root = [Link]()
# Create frames for organization
top_frame = [Link](root, bg="lightblue", height=100)
top_frame.pack(side="top", fill="x")
bottom_frame = [Link](root, bg="lightgreen", height=100)
bottom_frame.pack(side="bottom", fill="x")
# Add widgets to frames
[Link](top_frame, text="Top Frame", bg="lightblue").pack()
[Link](bottom_frame, text="Bottom Frame", bg="lightgreen").pack()
[Link]()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 14
Tkinter Widgets Summary Table
Widget Purpose / Use Syntax Example
Label Display text or Label(parent, Label(root,
image text="...") text="Hello!")
Button Creates a Button(parent, Button(root,
clickable button text="...", text="Click",
command=...) command=action)
Entry Single-line text Entry(parent) Entry(root)
input
Text Multi-line text Text(parent) Text(root, height=5,
input width=30)
Checkbutton Create a Checkbutton(parent, Checkbutton(root,
checkbox text="...") text="I agree")
Radiobutton Create radio Radiobutton(parent, Radiobutton(root,
buttons (select text="...", value=..., text="Male", value=1,
one option) variable=...) variable=gender)
Listbox Display a list of Listbox(parent) Listbox(root, height=4)
options
Scale Slider for Scale(parent, from_=x, Scale(root, from_=0,
selecting to=y) to=100)
numerical values
Spinbox Numeric spinner Spinbox(parent, Spinbox(root, from_=1,
from_=x, to=y) to=10)
Frame Container to Frame(parent) Frame(root, bg="blue")
group widgets
Canvas Drawing shapes, Canvas(parent) Canvas(root, width=200,
images height=100)
Toplevel Create a new Toplevel(parent) Toplevel(root)
window
Message Display multiline Message(parent, Message(root,
text like Label text="...") text="Welcome!")
Menu Create menu bar Menu(parent) Menu(root)
or context menu
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 15
3.7 Widget Attributes
Common Widget Attributes
Appearance Attributes
import tkinter as tk
root = [Link]()
# Color attributes
label = [Link](root,
text="Sample Text",
bg="lightblue", # Background color
fg="darkblue", # Foreground/text color
activebackground="blue", # Color when active
activeforeground="white") # Text color when active
# Font attributes
[Link](font=("Arial", 14, "bold")) # Font family, size, style
# Size attributes
[Link](width=20, height=3) # Width in characters, height in lines
# Border attributes
[Link](bd=2, relief="solid") # Border width and style
[Link]()
[Link]()
Positioning Attributes
import tkinter as tk
root = [Link]()
# Padding attributes
label = [Link](root, text="Padded Label", bg="yellow")
[Link](padx=20, pady=10) # External padding
# Internal padding
[Link](ipadx=10, ipady=5) # Internal padding
# Alignment attributes
[Link](anchor="w") # Align text to west (left)
[Link]()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 16
State Attributes
import tkinter as tk
root = [Link]()
# Button states
button = [Link](root, text="Click Me")
[Link]()
# Disable button
[Link](state="disabled")
# Enable button
# [Link](state="normal")
[Link]()
Tkinter Widget Attributes: Summary Table
Attribute Purpose / Use Common Widgets Example
text Sets the label or button name Label, Button, text="Click Me"
Checkbutton
bg / Background color Most widgets bg="lightblue"
background
fg / Text color Most widgets fg="red"
foreground
font Font style/size Label, Button, font=("Arial", 14,
Entry "bold")
width Width of widget (chars or pixels) Entry, Button, width=20
Text
height Height (for some widgets like Text, Canvas height=5
Text, Canvas)
command Function to call on click Button, command=submit_data
Checkbutton,
Menu
state Normal or disabled Button, Entry, state="disabled"
Checkbutton
relief 3D look (flat, raised, sunken, Most widgets relief="groove"
etc.)
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 17
anchor Text alignment (n, ne, e, se, s, Label, Button anchor="w"
sw, w, nw, center)
justify Text alignment (left, center, right) Label, Message justify="center"
padx, pady Padding around widget All widgets padx=10, pady=5
bd Border width All widgets bd=2
variable Store value (used in Entry, Entry, variable=my_var
Radiobutton etc.) Checkbutton,
Radiobutton
show Mask text (for passwords) Entry show="*"
Example Code Using Common Widgets and Attributes
import tkinter as tk
def show_name():
label_result.config(text="Hello " + entry_name.get())
root = [Link]()
[Link]("Simple Form")
[Link]("300x150")
label_name = [Link](root, text="Enter Name:", font=("Arial", 12))
label_name.pack(pady=5)
entry_name = [Link](root, width=25, bg="lightyellow")
entry_name.pack()
btn_submit = [Link](root, text="Submit", command=show_name, bg="green",
fg="white")
btn_submit.pack(pady=10)
label_result = [Link](root, text="", font=("Arial", 12, "bold"))
label_result.pack()
[Link]()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 18
Complete Example: Student Management System
import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
class StudentManagementSystem:
def __init__(self, root):
[Link] = root
[Link]("Student Management System")
[Link]("600x400")
# Initialize database
self.init_database()
# Create GUI
self.create_widgets()
def init_database(self):
[Link] = [Link]('[Link]')
[Link] = [Link]()
[Link]('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
grade TEXT)''')
[Link]()
def create_widgets(self):
# Input frame
input_frame = [Link]([Link])
input_frame.pack(pady=10)
[Link](input_frame, text="Name:").grid(row=0, column=0,
sticky="e", padx=5)
self.name_entry = [Link](input_frame)
self.name_entry.grid(row=0, column=1, padx=5)
[Link](input_frame, text="Age:").grid(row=1, column=0,
sticky="e", padx=5)
self.age_entry = [Link](input_frame)
self.age_entry.grid(row=1, column=1, padx=5)
[Link](input_frame, text="Grade:").grid(row=2, column=0,
sticky="e", padx=5)
self.grade_entry = [Link](input_frame)
self.grade_entry.grid(row=2, column=1, padx=5)
# Button frame
button_frame = [Link]([Link])
button_frame.pack(pady=10)
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 19
[Link](button_frame, text="Add Student",
command=self.add_student).pack(side="left", padx=5)
[Link](button_frame, text="Update Student",
command=self.update_student).pack(side="left", padx=5)
[Link](button_frame, text="Delete Student",
command=self.delete_student).pack(side="left", padx=5)
[Link](button_frame, text="Clear",
command=self.clear_entries).pack(side="left", padx=5)
# Treeview for displaying students
[Link] = [Link]([Link], columns=("ID", "Name", "Age",
"Grade"), show="headings")
[Link]("ID", text="ID")
[Link]("Name", text="Name")
[Link]("Age", text="Age")
[Link]("Grade", text="Grade")
[Link](fill="both", expand=True, padx=10, pady=10)
# Bind selection event
[Link]('<<TreeviewSelect>>', self.on_select)
# Load initial data
self.load_data()
def add_student(self):
name = self.name_entry.get()
age = self.age_entry.get()
grade = self.grade_entry.get()
if name and age and grade:
try:
[Link]("INSERT INTO students (name, age,
grade) VALUES (?, ?, ?)",
(name, int(age), grade))
[Link]()
self.load_data()
self.clear_entries()
[Link]("Success", "Student added
successfully!")
except ValueError:
[Link]("Error", "Please enter a valid age!")
else:
[Link]("Error", "Please fill all fields!")
def update_student(self):
selected_item = [Link]()
if selected_item:
student_id = [Link](selected_item)['values'][0]
name = self.name_entry.get()
age = self.age_entry.get()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 20
grade = self.grade_entry.get()
if name and age and grade:
try:
[Link]("UPDATE students SET name=?, age=?,
grade=? WHERE id=?",
(name, int(age), grade, student_id))
[Link]()
self.load_data()
self.clear_entries()
[Link]("Success", "Student updated
successfully!")
except ValueError:
[Link]("Error", "Please enter a valid
age!")
else:
[Link]("Error", "Please fill all fields!")
else:
[Link]("Error", "Please select a student to
update!")
def delete_student(self):
selected_item = [Link]()
if selected_item:
student_id = [Link](selected_item)['values'][0]
result = [Link]("Confirm", "Are you sure you want
to delete this student?")
if result:
[Link]("DELETE FROM students WHERE id=?",
(student_id,))
[Link]()
self.load_data()
self.clear_entries()
[Link]("Success", "Student deleted
successfully!")
else:
[Link]("Error", "Please select a student to
delete!")
def clear_entries(self):
self.name_entry.delete(0, [Link])
self.age_entry.delete(0, [Link])
self.grade_entry.delete(0, [Link])
def on_select(self, event):
selected_item = [Link]()
if selected_item:
values = [Link](selected_item)['values']
self.name_entry.delete(0, [Link])
self.name_entry.insert(0, values[1])
self.age_entry.delete(0, [Link])
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 21
self.age_entry.insert(0, values[2])
self.grade_entry.delete(0, [Link])
self.grade_entry.insert(0, values[3])
def load_data(self):
# Clear existing data
for item in [Link].get_children():
[Link](item)
# Load data from database
[Link]("SELECT * FROM students")
rows = [Link]()
for row in rows:
[Link]("", "end", values=row)
def __del__(self):
if hasattr(self, 'conn'):
[Link]()
if __name__ == "__main__":
root = [Link]()
app = StudentManagementSystem(root)
[Link]()
Prepared By: Nisha D. Desai UNIT : 3 PYTHON INTERACTION WITH SQLite 22