ipython-sql
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
- breaking ipython-sql is a 'Legacy project' with development shifted to JupySQL. For new projects or advanced features, consider using JupySQL, which is its maintained successor.
- breaking Incompatible with SQLAlchemy 2.x. Users upgrading SQLAlchemy to version 2.0 or newer may encounter errors.
- gotcha Database drivers (e.g., psycopg2, pymysql) are NOT installed with `ipython-sql` by default. You must install the appropriate driver separately for your chosen database.
- gotcha Common `ImportError` or `UsageError: Line magic function `%sql` not found` when running `%load_ext sql`. This often indicates that `ipython-sql` was installed in a different Python environment or Jupyter kernel than the one currently active.
- gotcha Query results are loaded as lists into memory. Very large result sets can consume significant memory, potentially causing the notebook or browser to hang.
- deprecated Older `prettytable` configuration (e.g., `c.SqlMagic.style`) may cause `KeyError: "DEFAULT"` due to deprecated options.
- gotcha Variable substitution: Using `:variable_name` creates bind parameters passed to the SQL engine (recommended for data). Using `$variable_name` or `{variable_name}` directly substitutes the value into the SQL string before execution (can be a SQL injection risk for untrusted input). Using `${variable_name}` (both) is not supported.
Install
-
pip install ipython-sql -
pip install ipython-sql [postgresql] -
pip install ipython-sql [mysql] -
pip install ipython-sql [duckdb]
Imports
- %load_ext sql
%load_ext sql
- %sql
%sql sqlite:///:memory:
- %%sql
%%sql SELECT * FROM my_table;
Quickstart
# 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)