ipython-sql

0.5.0 · maintenance · verified Wed Apr 15

ipython-sql provides SQL magic commands (`%sql` and `%%sql`) to seamlessly integrate SQL queries and database interactions directly within IPython and Jupyter Notebook environments. It leverages SQLAlchemy for database connections and supports various RDBMS. The current version is 0.5.0. Development has largely shifted to its successor, JupySQL, making ipython-sql a legacy project primarily in maintenance mode.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load the `ipython-sql` extension, connect to an in-memory SQLite database, create a table, insert data, and perform a basic select query. It also shows how to use bind parameters for secure variable substitution in queries.

# Load the ipython-sql extension
%load_ext sql

# Connect to an in-memory SQLite database
%sql sqlite:///:memory:

# Create a table
%%sql
CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name VARCHAR(50),
    email VARCHAR(100)
);

# Insert data into the table
%%sql
INSERT INTO users (name, email) VALUES
    ('Alice', 'alice@example.com'),
    ('Bob', 'bob@example.com');

# Select data from the table
result = %sql SELECT * FROM users;
print(result)

# Demonstrate variable substitution (bind parameters)
user_id = 1
user_name = 'Charlie'

# Using bind parameters (:variable)
user_from_db = %sql SELECT * FROM users WHERE id = :user_id;
print(f"User with ID {user_id}: {user_from_db}")

# Using direct substitution ($variable) - use with caution for dynamic SQL
# (Note: %sql --persist is also available for pandas DataFrames)

view raw JSON →