-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlmagic.py
More file actions
59 lines (45 loc) · 1.55 KB
/
sqlmagic.py
File metadata and controls
59 lines (45 loc) · 1.55 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Author: Aiyesha Ma & Marcos Sainz
Tested on IPython version 0.13.1
This SQL cell magic allows you to open multiple connections to several
databases and then reference the connections by name inside IPython
Adapted from:
- https://gist.github.com/pfmoore/3872878
- https://gist.github.com/bmabey/4585890
Load using:
import sqlmagic
reload(sqlmagic) # useful if you plan to be modifying this file
Now you can do:
%connect {"name": "connection_name", "params": {"host": "host", "db": "database_name", "user": "user", "password": "password"}}
%%sql connection_name
select * from foo
"""
from IPython.core.magic import (Magics, magics_class, cell_magic, line_magic)
import MySQLdb
import json
# The class MUST call this class decorator at creation time
@magics_class
class SQLMagic(Magics):
connections = {}
@line_magic
def connect(self, line):
"Connect to a database"
args = json.loads(line)
connection_name = args['name'].strip()
params = args['params']
pwd = params['password'] if 'password' in params else ''
self.connections[connection_name] = MySQLdb.connect(
host=params['host'],
user=params['user'],
passwd=pwd ,
db=params['db'])
print "Connected successfully"
@cell_magic
def sql(self, line, cell):
"Run a SQL query"
c = self.connections[line.strip()].cursor()
c.execute(cell)
return c.fetchall()
#This registers the SQLMagic class
ip = get_ipython()
ip.register_magics(SQLMagic)