Skip to content

Instantly share code, notes, and snippets.

@pfmoore pfmoore/
Created Oct 11, 2012

What would you like to do?
Simple ipython SQL magic
# This code can be put in any Python module, it does not require IPython
# itself to be running already. It only creates the magics subclass but
# doesn't instantiate it yet.
from IPython.core.magic import (Magics, magics_class, line_magic,
cell_magic, line_cell_magic)
import sqlite3
# The class MUST call this class decorator at creation time
class MyMagics(Magics):
cn = None
def connect(self, line):
"Connect to a database" = sqlite3.connect(line)
def sql(self, line, cell):
"Run a SQL query"
c =
return c.fetchall()
# Install using
# import <thisfile>
# ip = get_ipython()
# ip.register_magics(<thisfile>.MyMagics)
# Now you can do:
# %connect :memory:
# %%sql
# create table foo (n number)
# %%sql
# insert into foo values(1)
# etc...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.