*.ipynb: Use absolute URLs to link to the glossary
[swc-sql.git] / sqlitemagic.py
1 """sqlitemagic provices a simple magic for interacting with SQLite
2 databases stored on disk.
3
4 Usage:
5
6 %%sqlite filename.db
7 select personal, family from person;
8
9 produces:
10
11 Alan|Turing
12 Grace|Hopper
13 """
14
15 # This file is copyright 2013 by Greg Wilson: see
16 # https://github.com/gvwilson/sqlitemagic/blob/master/LICENSE
17 # for the license.
18 # Inspired by https://github.com/tkf/ipython-sqlitemagic.
19
20 import sqlite3
21 from IPython.core.magic import Magics, magics_class, cell_magic
22 from IPython.display import display, HTML
23
24 @magics_class
25 class SqliteMagic(Magics):
26     '''Provide the 'sqlite' calling point.'''
27
28     @cell_magic
29     def sqlite(self, filename, query):
30         connection = sqlite3.connect(filename)
31         cursor = connection.cursor()
32         try:
33             cursor.execute(query)
34             results = cursor.fetchall()
35             display(HTML(self.tablify(results)))
36         except Exception, e:
37             import sys
38             print >> sys.stderr, "exception", e
39         cursor.close()
40         connection.close()
41
42     def tablify(self, rows):
43         return '<table>\n' + '\n'.join(self.rowify(r) for r in rows) + '\n</table>'
44
45     def rowify(self, row):
46         return '<tr>' + ''.join('<td>' + str(r) + '</td>' for r in row) + '</tr>'
47
48 def load_ipython_extension(ipython):
49     ipython.register_magics(SqliteMagic)