public
Created

Simple ipython SQL magic

  • Download Gist
sqlmagic.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
# 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
@magics_class
class MyMagics(Magics):
cn = None
 
@line_magic
def connect(self, line):
"Connect to a database"
self.cn = sqlite3.connect(line)
 
@cell_magic
def sql(self, line, cell):
"Run a SQL query"
c = self.cn.cursor()
c.execute(cell)
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...

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.