1 """sqlitemagic provices a simple magic for interacting with SQLite
2 databases stored on disk.
7 select personal, family from person;
15 # This file is copyright 2013 by Greg Wilson: see
16 # https://github.com/gvwilson/sqlitemagic/blob/master/LICENSE
18 # Inspired by https://github.com/tkf/ipython-sqlitemagic.
21 from IPython.core.magic import Magics, magics_class, cell_magic
22 from IPython.display import display, HTML
25 class SqliteMagic(Magics):
26 '''Provide the 'sqlite' calling point.'''
29 def sqlite(self, filename, query):
30 connection = sqlite3.connect(filename)
31 cursor = connection.cursor()
34 results = cursor.fetchall()
35 display(HTML(self.tablify(results)))
38 print >> sys.stderr, "exception", e
42 def tablify(self, rows):
43 return '<table>\n' + '\n'.join(self.rowify(r) for r in rows) + '\n</table>'
45 def rowify(self, row):
46 return '<tr>' + ''.join('<td>' + str(r) + '</td>' for r in row) + '</tr>'
48 def load_ipython_extension(ipython):
49 ipython.register_magics(SqliteMagic)