Skip to content

Python driver

View as Markdown

pycoradb is the Python driver for CoraDB. It implements the standard DB-API 2.0 (PEP 249) interface — connect(), cursor(), execute(), fetch*(), commit() — so it works like other Python database drivers and with tools built on DB-API. It is written in pure Python and speaks the CoraDB broker protocol directly: nothing to compile, no client library to install.

  • ? (qmark) parameters; a list bound to one ? expands into a value list, so WHERE id IN (?) works.
  • All data types: NUMERIC as Decimal, time-zone types as aware datetime, JSON, ENUM, BIT, collections, BLOB/CLOB through a Lob object.
  • TLS, ping() with automatic reconnect, batch execution with executemany(), schema information, optional timing statistics, type hints (py.typed).

Requires Python 3.10 or newer. On Windows the tzdata package is installed with it, for the time-zone database.

pip install . # from a checkout of the pycoradb repository
import pycoradb
conn = pycoradb.connect(host="localhost", port=33000, database="e-commerce",
user="dba", password="", read_timeout=30)
print(conn.get_server_version())
Option Default Meaning
host, port "localhost", 33000 Broker address.
database, user, password "", "dba", "" Database and credentials.
charset "utf-8" Encoding of SQL text and strings; set it to the database charset.
autocommit False Turn auto-commit on after connecting (DB-API default is off).
connect_timeout, read_timeout None Seconds for session setup / for each request.
ssl None True for TLS with the system trust store, or an ssl.SSLContext.
decode_collections False Decode SET / MULTISET / SEQUENCE values (otherwise raw bytes).
json_deserializer None For example json.loads, to get JSON columns as Python objects.
zero_date_behavior "exception" "exception", "convert_to_null" or "round" for 0000-00-00.
fetch_size 100 Rows per network round trip.

All options are described in the API reference.

cur = conn.cursor()
cur.execute("SELECT name, unit_price FROM product WHERE unit_price > ? ORDER BY unit_price DESC LIMIT 3",
(90,))
for name, price in cur.fetchall():
print(name, price) # Côte de Blaye 263.50 (price is a decimal.Decimal)

A graph query is an ordinary statement:

cur.execute("""
SELECT b.name AS brand, COUNT(cu) AS followers
FROM MATCH (cu:customer)-[:follows]->(b:brand)
GROUP BY b.name ORDER BY followers DESC LIMIT ?""", (3,))
print(cur.fetchall()) # [('Nike', 209), ('Adidas', 132), ('Puma', 94)]

A list fills an IN clause:

cur.execute("SELECT code, name FROM countries WHERE code IN (?) ORDER BY name", (["FRA", "DEU", "ITA"],))

cursor.description describes the result columns, rowcount gives the rows changed by the last INSERT/UPDATE/DELETE, and lastrowid the last AUTO_INCREMENT value. A cursor is iterable and is a context manager.

Auto-commit is off by default, as DB-API requires: call commit() or rollback(). Used as a context manager, a connection commits on success, rolls back on error and closes:

with pycoradb.connect(database="e-commerce", user="dba") as conn:
with conn.cursor() as cur:
cur.execute("INSERT INTO orders (id, customer_id, order_date, shipping_cost, ship_address) "
"VALUES (?, ?, SYSDATE, ?, ?)", (9001, 5, Decimal("4.90"), "Storgatan 1, Luleå"))
cur.execute("INSERT INTO order_items (order_id, product_id, quantity, discount_pct) "
"VALUES (?, ?, ?, 0)", (9001, 1379, 2))
# committed here, or rolled back if an exception was raised

executemany() sends INSERT, UPDATE and DELETE statements to the server as one batch request:

cur.executemany("UPDATE product SET units_in_stock = units_in_stock + ? WHERE id = ?",
[(10, 1379), (5, 1224)])
conn.commit()

pycoradb raises the standard DB-API exceptions: IntegrityError (unique, primary key, foreign key, NOT NULL), ProgrammingError (syntax, unknown objects, wrong parameter count), DataError, OperationalError (connection lost, timeout, broker refused, TLS), InternalError, NotSupportedError, InterfaceError. Server errors carry errno (for example -670) and sqlstate.

try:
cur.execute("INSERT INTO countries (code, name) VALUES (?, ?)", ("FRA", "France"))
except pycoradb.IntegrityError as e:
print(e.errno, e.msg)
conn.rollback()

pycoradb is a port of pycubrid 1.8 with the same DB-API interface:

  • Replace import pycubrid with import pycoradb; public identifiers are renamed CUBRID* → CoraDB* (CoraDBDataType, CoraDBStatementType, CoraDBIsolationLevel …), and the timing switch is PYCORADB_ENABLE_TIMING.
  • The asyncio API (pycubrid.aio) and the CUBRIDdb compatibility layer are not included.
  • Lists and tuples bound to one ? are now expanded into value lists (pycubrid rejected them).
  • An unknown connect() option is ignored with an UnknownConnectionOptionWarning.

Applications written for the old CCI-based CUBRIDdb module use the same DB-API calls and switch to pycoradb.connect().

The complete API — connect(), Connection, Cursor, Lob, parameter binding and result types, zero dates, type objects, exceptions, timing statistics and constants — is in the Python driver API reference.