Connecting to a Database

Each backend lives in its own submodule, and the class shares its name.

MySQL

from easymysql.mysql import mysql

db = mysql('localhost', 'user', 'password', 'mydb')

PostgreSQL

Requires the extra: pip install easymysql[postgres].

from easymysql.postgres import postgresql

db = postgresql('localhost', 'user', 'password', 'mydb')
Import from the submodule, not from the package

from easymysql import mysql does not fail on the import line: it hands you the module easymysql.mysql, and the error shows up when you call it — TypeError: 'module' object is not callable. from easymysql import postgresql raises ImportError. Use the submodule, or the capitalised aliases below.

Capitalised aliases

MySQL and PostgreSQL are the same classes, importable from the package:

from easymysql import MySQL, PostgreSQL, WriteResult

db = MySQL('localhost', 'user', 'password', 'mydb')

The PostgreSQL driver is imported only when PostgreSQL is used, so MySQL works without psycopg2 installed.

The four parameters

They are positional and required, in this order: host, user, password, database.

Driver options

Any extra keyword argument is passed straight to the underlying driver:

db = mysql('localhost', 'user', 'password', 'mydb',
           port=3306, connect_timeout=5, charset='utf8mb4')

pg = postgresql('localhost', 'user', 'password', 'mydb',
                port=5432, sslmode='require')
Backend Common options
MySQL port, charset, ssl, connect_timeout, read_timeout, unix_socket, client_flag
PostgreSQL port, sslmode, connect_timeout, application_name

charset defaults to utf8mb4 on MySQL.

Context manager

Both classes close themselves on the way out of the block:

with mysql('localhost', 'user', 'password', 'mydb') as db:
    rows = db.select('users')

Lifecycle

db.connect()      # opens the connection, or keeps a healthy one
db.close()        # closes it
db.reconnect()    # closes the old one, then opens a new one
db.ping()         # -> bool, is the connection alive?

connect() on a healthy connection keeps it and returns. On an instance that was closed with close(), it opens a new connection. No other method reopens a closed instance.

reconnect() replaces the session and never repeats a statement. Both connect() and reconnect() raise RuntimeError when:

In each case, the owning thread calls commit(), rollback() or close() first.

No automatic reconnection or retry

A driver exception propagates as it is. The statement was sent once, and neither the statement nor a commit is repeated:

try:
    db.insert('users', {'email': '[email protected]'})
except Exception:
    ...   # sent once; reconcile before repeating it
    db.reconnect()      # explicit

A lost response does not mean the write or the commit failed on the server. Check the state before repeating the operation. Closing and reconnecting does not undo a commit the server already applied.

Resetting the session

db.resetSession()
db.reset_session()   # same method

Returns the session to the state it had when freshly connected: temporary tables, user variables, prepared statements and the rest of the session state are gone. On MySQL it reconnects; on PostgreSQL it runs DISCARD ALL.

It requires a clean session and commits nothing to get there. It raises RuntimeError with a transaction open, and with pending work outside transaction() — see Transactions.