Skip to content

Instantly share code, notes, and snippets.

@bmabey
Last active December 11, 2015 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmabey/4585890 to your computer and use it in GitHub Desktop.
Save bmabey/4585890 to your computer and use it in GitHub Desktop.
Simple cell and line IPython Notebook magics for connecting to a ODBC DB and querying
from IPython.core.magic import (Magics, magics_class, line_magic,
cell_magic, line_cell_magic)
import pyodbc
import pandas.io.sql as sql
@magics_class
class SQLMagic(Magics):
con = None
def __init__(self, shell):
super(SQLMagic, self).__init__(shell)
@line_magic
def odbc(self, line):
"Connect to an ODBC database (DSN) configured in your odbc.ini"
self.con = pyodbc.connect('DSN='+line.strip())
@line_cell_magic
def sql(self, line, cell=None):
"Run a SQL query"
query = None
if cell:
query = cell
else:
query = line
df = sql.read_frame(query, self.con)
self.shell.push({'last_df': df})
return df
def load_ipython_extension(ip):
ip.register_magics(SQLMagic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment