0% found this document useful (0 votes)
71 views

SQLITE3 FOR PYTHON

The document provides a comprehensive guide on using SQLite3 with Python, covering database connection, table creation, data insertion, querying, updating, and deleting records. It demonstrates the use of the 'with' statement for automatic connection management and includes examples of using the Faker library for generating fake data. Additionally, it explains transaction management and includes a funds transfer operation between customers.

Uploaded by

joshismita174
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

SQLITE3 FOR PYTHON

The document provides a comprehensive guide on using SQLite3 with Python, covering database connection, table creation, data insertion, querying, updating, and deleting records. It demonstrates the use of the 'with' statement for automatic connection management and includes examples of using the Faker library for generating fake data. Additionally, it explains transaction management and includes a funds transfer operation between customers.

Uploaded by

joshismita174
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

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()

WITH STATEMENT (NO NEED TO EXPLICITLY CLOSE THE CONNECTION


import sqlite3
# Step 1: Use 'with' to connect to the database (or create one) and automatically close it
when done
with sqlite3.connect('my_database.db') as connection:
# Step 2: Create a cursor object to interact with the database
cursor = connection.cursor()
print("Database created and connected successfully!")
# No need to call connection.close(); it's done automatically!

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.

cursor.execute("BEGIN;") # transaction begins implicitly


Connection.commit() # saves all the changes made during a transaction
Connection.rollback() #revert the changes made during a transcation

# CREATION OF TABLE FOR EG:


import sqlite3
# Create the Customers table and add two customers
with sqlite3.connect('my_database.db') as connection:
cursor = connection.cursor()
# Create Customers table
create_customers_table = '''
CREATE TABLE IF NOT EXISTS Customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
balance REAL NOT NULL
);
'''
cursor.execute(create_customers_table)
# Insert two customers
cursor.execute(
"INSERT INTO Customers (name, balance) VALUES (?, ?);", ('Ashutosh', 100.0))
cursor.execute(
"INSERT INTO Customers (name, balance) VALUES (?, ?);", ('Krishna', 50.0))
connection.commit()

#FUNDS TRNASFTER OPERATION BETWEEN ASHUTOSH AND KRISHNA


import sqlite3
def transfer_funds(from_customer, to_customer, amount):
with sqlite3.connect('my_database.db') as connection:
cursor = connection.cursor()
try:
# Start a transaction
cursor.execute("BEGIN;")
# Deduct amount from the sender
cursor.execute(
"UPDATE Customers SET balance = balance - ? WHERE name = ?;", (amount,
from_customer))
# Add amount to the receiver
cursor.execute(
"UPDATE Customers SET balance = balance + ? WHERE name = ?;", (amount,
to_customer))
# Commit the changes
connection.commit()
print(
f"Transferred {amount} from {from_customer} to {to_customer}.")
except Exception as e:
# If an error occurs, rollback the transaction
connection.rollback()
print(f"Transaction failed: {e}")
# Example usage
transfer_funds('Ashutosh', 'Krishna', 80.0)

You might also like