SQLITE3 FOR PYTHON
SQLITE3 FOR PYTHON
import sqlite3
# Connect to the SQLite database (or create it if it doesn't exist)
connection = sqlite3.connect('my_database.db')
# Create a cursor object- for executing commands
cursor = connection.cursor()
# Close the database connection
connection.close()
CREATION OF A TABLE
import sqlite3
# Use 'with' to connect to the SQLite database and automatically close the connection when
done
with sqlite3.connect('my_database.db') as connection:
# Create a cursor object
cursor = connection.cursor()
# Write the SQL command to create the Students table
create_table_query = '''
CREATE TABLE IF NOT EXISTS Students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT
);
'''
# Execute the SQL command
cursor.execute(create_table_query)
# Commit the changes
connection.commit()
# Print a confirmation message
print("Table 'Students' created successfully!")
INSERTION OF A SINGLE RECORD
INSERT INTO Students (name, age, email)
VALUES ('John Doe', 20, '[email protected]');
import sqlite3
# Use 'with' to open and close the connection automatically
with sqlite3.connect('my_database.db') as connection:
cursor = connection.cursor()
# Insert a record into the Students table
insert_query = '''
INSERT INTO Students (name, age, email)
VALUES (?, ?, ?);
'''
student_data = ('Jane Doe', 23, '[email protected]')
cursor.execute(insert_query, student_data)
# Commit the changes automatically
connection.commit()
# No need to call connection.close(); it's done automatically!
print("Record inserted successfully!")
INSERT MULTIPLE RECORDS
from faker import Faker
import sqlite3
# Initialize Faker
fake = Faker(['en_IN'])
# Use 'with' to open and close the connection automatically
with sqlite3.connect('my_database.db') as connection:
cursor = connection.cursor()
# Insert a record into the Students table
insert_query = '''
INSERT INTO Students (name, age, email)
VALUES (?, ?, ?);
'''
students_data = [(fake.name(), fake.random_int(
min=18, max=25), fake.email()) for _ in range(5)]
# Execute the query for multiple records
cursor.executemany(insert_query, students_data)
# Commit the changes
connection.commit()
# Print confirmation message
print("Fake student records inserted successfully!")
QUERY DATA
SELECT * FROM Students;
import sqlite3
# Use 'with' to connect to the SQLite database
with sqlite3.connect('my_database.db') as connection:
# Create a cursor object
cursor = connection.cursor()
# Write the SQL command to select all records from the Students table
select_query = "SELECT * FROM Students;"
# Execute the SQL command
cursor.execute(select_query)
# Fetch all records
all_students = cursor.fetchall()
# Display results in the terminal
print("All Students:")
for student in all_students:
print(student)
import sqlite3
# Use 'with' to connect to the SQLite database
with sqlite3.connect('my_database.db') as connection:
# Create a cursor object
cursor = connection.cursor()
# Write the SQL command to select all records from the Students table
select_query = "SELECT * FROM Students;"
# Execute the SQL command
cursor.execute(select_query)
# Fetch one record
student = cursor.fetchone()
# Display the result
print("First Student:")
print(student)
import sqlite3
# Use 'with' to connect to the SQLite database
with sqlite3.connect('my_database.db') as connection:
# Create a cursor object
cursor = connection.cursor()
# Write the SQL command to select all records from the Students table
select_query = "SELECT * FROM Students;"
# Execute the SQL command
cursor.execute(select_query)
# Fetch three records
three_students = cursor.fetchmany(3)
# Display results
print("Three Students:")
for student in three_students:
print(student)
USING PANDAS
import sqlite3
import pandas as pd
# Use 'with' to connect to the SQLite database
with sqlite3.connect('my_database.db') as connection:
# Write the SQL command to select all records from the Students table
select_query = "SELECT * FROM Students;"
# Use pandas to read SQL query directly into a DataFrame- for better representation
df = pd.read_sql_query(select_query, connection)
# Display the DataFrame
print("All Students as DataFrame:")
print(df)
UPDATE DATA
import sqlite3
# Use 'with' to connect to the SQLite database
with sqlite3.connect('my_database.db') as connection:
cursor = connection.cursor()
# SQL command to update a student's age
update_query = '''
UPDATE Students
SET age = ?
WHERE name = ?;
'''
# Data for the update
new_age = 21
student_name = 'Jane Doe'
# Execute the SQL command with the data
cursor.execute(update_query, (new_age, student_name))
# Commit the changes to save the update
connection.commit()
# Print a confirmation message
print(f"Updated age for {student_name} to {new_age}.")
DELETE DATA
import sqlite3
# Use 'with' to connect to the SQLite database
with sqlite3.connect('my_database.db') as connection:
cursor = connection.cursor()
# SQL command to delete a student
delete_query = '''
DELETE FROM Students
WHERE name = ?;
'''
# Name of the student to be deleted
student_name = 'Jane Doe'
# Execute the SQL command with the data
cursor.execute(delete_query, (student_name,))
# Commit the changes to save the deletion
connection.commit()
# Print a confirmation message
print(f"Deleted student record for {student_name}.")
TRANSACTION IN PYTHON
In SQLite, transactions are managed using the BEGIN, COMMIT, and ROLLBACK commands.
However, when using the sqlite3 module in Python, you typically manage transactions
through the connection object.