public
Last active

Simple cell and line IPython Notebook magics for connecting to a ODBC DB and querying

  • 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
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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.