165. Working with sqlite3 Database

Snippet 1: Connecting to an SQLite Database

Copy

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

Copy

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

Copy


Snippet 4: Retrieving Data from a Table

Copy


Snippet 5: Updating Data in a Table

Copy


Snippet 6: Deleting Data from a Table

Copy


Snippet 7: Using Placeholders to Prevent SQL Injection

Copy


Snippet 8: Using a Context Manager for Connections

Copy


Snippet 9: Using Row Factory for Named Columns

Copy


Snippet 10: Dropping a Table

Copy


Last updated