165. Working with sqlite3 Database

Snippet 1: Connecting to an SQLite Database

import sqlite3

# Connect to the database (creates the file if it doesn't exist)
connection = sqlite3.connect("example.db")

# Print success message
print("Database connected successfully!")

# Close the connection
connection.close()

Snippet 2: Creating a Table

import sqlite3

# Connect to the database
connection = sqlite3.connect("example.db")
cursor = connection.cursor()

# Create a table
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER
)
""")
print("Table created successfully!")

# Commit changes and close the connection
connection.commit()
connection.close()

Snippet 3: Inserting Data into a Table


Snippet 4: Retrieving Data from a Table


Snippet 5: Updating Data in a Table


Snippet 6: Deleting Data from a Table


Snippet 7: Using Placeholders to Prevent SQL Injection


Snippet 8: Using a Context Manager for Connections


Snippet 9: Using Row Factory for Named Columns


Snippet 10: Dropping a Table


Last updated