Created
October 11, 2012 14:42
-
-
Save pfmoore/3872878 to your computer and use it in GitHub Desktop.
Simple ipython SQL magic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment