Last active
December 11, 2015 10:18
-
-
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
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
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