1. Prometheus Research, LLC
  2. Prometheus
  3. htsql

Source

htsql / doc / embed.rst

HTSQL in Python Applications

Table of Contents

HTSQL is a Python library which can be used to make HTSQL requests directly from Python applications.

Installation

You can install HTSQL with pip or easy_install package manager. For example, to install HTSQL using pip, run:

# pip install HTSQL

Alternatively, you can download HTSQL source package and install it manually.

You also need to install a database driver specific to the database server you are using. HTSQL requires the following driver libraries:

SQLite
sqlite3 (built-in Python module)
PostgreSQL
psycopg2
MySQL
MySQL-python
Oracle
cx_Oracle
Microsoft SQL Server
pymssql

Quick Start

Start with creating an instance of class :class:`htsql.HTSQL`. Pass the address of the database as the argument of the class constructor:

>>> from htsql import HTSQL
>>> htsql = HTSQL("pgsql:///htsql_demo")

To execute an HTSQL request and get output rows, use method :meth:`HTSQL.produce()`:

>>> rows = htsql.produce("/school{name, count(department)}")

:meth:`HTSQL.produce()` returns an iterator emitting output rows. You could access individual fields of an output row either by name (when it is specified) or by position:

>>> for row in rows:
...     print "%s: %s" % (row.name, row[1])
...
School of Art and Design: 2
School of Business: 3
College of Education: 2
School of Engineering: 4
School of Arts and Humanities: 5
School of Music & Dance: 4
School of Natural Sciences: 4
Public Honorariums: 0
School of Continuing Studies: 0

It is easy to pass parameters to the query:

>>> for row in htsql.produce("/department{name}?school.code=$school_code",
...                          school_code='ns'):
...     print row
...
department(name=u'Astronomy')
department(name=u'Chemistry')
department(name=u'Mathematics')
department(name=u'Physics')

In this example, the parameter school_code is available in the query as a reference $school_code.