In [1]:
import blaze

Connecting to a Database

In this tutorial we will use SQLite to make it easy to produce a self-contained, runable, tutorial.


In [2]:
import sqlite3 as db

Create schema:


In [3]:
conn = db.connect(":memory:")
c = conn.cursor()
c.execute('''create table TestTable
(id INTEGER PRIMARY KEY, content text, value real)''')


Out[3]:
<sqlite3.Cursor at 0x1149dd9d0>

Populate Test Table:


In [4]:
data = [
    (1,  "hello", 2.1),
    (2,  "world", 4.2),
    (3, "!",     8.4),
]

c.executemany("""insert into testtable
              values (?, ?, ?)""", data)
conn.commit()
c.close()

In [5]:
list(conn.execute("SELECT * from TestTable"))


Out[5]:
[(1, u'hello', 2.1), (2, u'world', 4.2), (3, u'!', 8.4)]

Connecting from Blaze

We can connect to an SQL database using the sql_table and sql_column functions.


In [6]:
from datashape import dshape
from blaze.io.sql import sql_table, sql_column

In [7]:
table = sql_table(
            'testtable',
            ['id', 'msg', 'price'],
            [dshape('int32'), dshape('string'), dshape('float64')],
            conn)

In [8]:
print table


<sql col testtable.* with shape var * { id : int32, msg : string, price : float64 }>

In [9]:
table['id']


Out[9]:
SQLDataDescriptor(testtable.id)

In [10]:
blaze.eval(table['id'])


Out[10]:
array([1, 2, 3],
      dshape='3 * int32')