General Python SDK: connection, exact values and transactions¶
This lab uses matrixone-python-sdk==0.1.16, not mo-vector. Follow the SDK installation/version guide and use a dedicated database. sdk_basics_lab must not exist. The script cleans up only a table it successfully creates; do not run it against business data.
Database and connection¶
CREATE DATABASE mo_python_sdk_lab;
Set MO_HOST, MO_PORT, MO_USER, MO_PASSWORD and MO_DATABASE, with MO_DATABASE=mo_python_sdk_lab. The usual local port is 6001; supply credentials through environment configuration. Set MO_SSL_CA for synchronous verified TLS; local acceptance does not certify remote TLS.
Run the complete script¶
Save as sdk_basics.py and run with Python. DDL stays outside the data transaction. SQLAlchemy text and Session bind values containing quotes, question marks, Unicode, zero bytes and exact numbers.
import os
from datetime import datetime
from decimal import Decimal
from importlib.metadata import version
from matrixone import Client
from sqlalchemy import text
client = Client(sql_log_mode="off", pool_size=2, max_overflow=0)
created = False
options = dict(host=os.getenv("MO_HOST", "127.0.0.1"),
port=int(os.getenv("MO_PORT", "6001")),
user=os.environ["MO_USER"], password=os.environ["MO_PASSWORD"],
database=os.environ["MO_DATABASE"], on_connect=[])
if os.getenv("MO_SSL_CA"):
options.update(ssl_mode="required", ssl_ca=os.environ["MO_SSL_CA"])
try:
client.connect(**options)
print("SDK:", version("matrixone-python-sdk"))
print("Server:", client.execute("SELECT VERSION()").scalar())
client.execute("CREATE TABLE sdk_basics_lab(id BIGINT PRIMARY KEY,"
"amount DECIMAL(38,18),label VARCHAR(100),raw_value VARBINARY(16),"
"event_at DATETIME(6))")
created = True
values = dict(id=1, amount=Decimal("12345678901234567890.123456789012345678"),
label="quote' question? Unicode😀", raw_value=bytes.fromhex("005CFF"),
event_at=datetime(2026, 1, 1, 8, 0, 0, 123456))
with client.session() as session:
session.execute(text("INSERT INTO sdk_basics_lab VALUES"
"(:id,:amount,:label,:raw_value,:event_at)"), values)
result = client.execute("SELECT * FROM sdk_basics_lab ORDER BY id")
assert tuple(result.fetchone()) == tuple(values.values())
assert result.fetchone() is None
try:
with client.session() as session:
session.execute(text("INSERT INTO sdk_basics_lab(id) VALUES(:id)"), {"id": 2})
raise RuntimeError("intentional rollback")
except RuntimeError as error:
assert str(error) == "intentional rollback"
assert client.execute("SELECT COUNT(*) FROM sdk_basics_lab").scalar() == 1
with client.session() as session:
session.execute(text("UPDATE sdk_basics_lab SET label=:label WHERE id=:id"),
{"label": "updated", "id": 1})
assert session.execute(text("SELECT label FROM sdk_basics_lab WHERE id=:id"),
{"id": 1}).scalar() == "updated"
session.execute(text("DELETE FROM sdk_basics_lab WHERE id=:id"), {"id": 1})
assert client.execute("SELECT COUNT(*) FROM sdk_basics_lab").scalar() == 0
print("exact values / rollback / update / delete verified")
finally:
try:
if created:
client.execute("DROP TABLE sdk_basics_lab")
finally:
client.disconnect()
Successful output includes SDK 0.1.16, server version and exact values / rollback / update / delete verified. The intentional error proves id=2 rolled back; UPDATE/DELETE are checked separately. Success means verified effects, not merely absence of exceptions.
Async reads¶
This separate script passes with SDK 0.1.16, SQLAlchemy 2.0.43, aiomysql 0.3.2 and PyMySQL 1.1.1. The ping failure with SQLAlchemy 2.0.43 / PyMySQL 1.2.3 occurs in client connection checks, not SQL support. This short example does not certify async TLS, concurrent writes or cancellation/retry semantics.
import asyncio
import os
from matrixone import AsyncClient
async def main():
client = AsyncClient(sql_log_mode="off")
try:
await client.connect(host=os.getenv("MO_HOST", "127.0.0.1"),
port=int(os.getenv("MO_PORT", "6001")),
user=os.environ["MO_USER"], password=os.environ["MO_PASSWORD"],
database=os.environ["MO_DATABASE"], on_connect=[])
result = await client.execute("SELECT VERSION()")
print(result.scalar())
finally:
await client.disconnect()
asyncio.run(main())
In a Notebook with a running event loop, use await main() rather than nesting asyncio.run. AsyncResultSet fetch/scalar methods access already fetched memory; each call is not another awaited network fetch.
Continue and troubleshoot¶
Distinguish missing databases, authentication, TLS and dependencies for connection errors; binding, types, privileges and SQL for query errors. Record distribution/server versions and protect SQL/data in error logs. Do not ignore exceptions and mark a batch successful.
Separate ordinary client.execute calls commit independently. One Session provides the tested shared DML rollback boundary. Re-running refuses an existing table rather than using drop_existing_table or if_exists=replace. Aggregate/page large results first: fetchmany does not turn ResultSet into a server cursor.
Other capabilities and boundaries are in the SDK guide. These blocks executed on Python 3.12.14 / MO v4.2.5 on 2026-10-14; they do not certify every dependency combination.