Connecting to a Database

Import the mysql class and create an instance by passing your connection credentials. The constructor calls connect() immediately, so the connection and its cursor are open by the time the constructor returns.

from easymysql.mysql import mysql

db = mysql(hostname, username, password, database)

Parameters

Parameter Type Description
hostname str MySQL server hostname or IP address
username str Database user
password str Database password
database str Name of the database to use

These are the exact keyword names accepted by the constructor. If you prefer keyword arguments, write mysql(hostname='localhost', username='root', …) — note hostname and username, not host and user.

There is no port parameter. The underlying PyMySQL connection uses the default port 3306; to reach a server on another port you need a raw PyMySQL connection instead of EasyMySQL.

Example

from easymysql.mysql import mysql

db = mysql('localhost', 'root', 'secret', 'shop')

After this line, db is ready to use. All subsequent operations — insert, select, update, delete — are called as methods on this object.

Staying connected

EasyMySQL keeps the credentials on the instance and reconnects on its own. Every execute() and query() call — and therefore every select(), insert(), update() and delete() — first pings the server and reconnects if the ping fails. Long-running scripts survive MySQL's wait_timeout without any handling on your side.

Method Returns Description
connect() None Opens the connection and a fresh cursor using the stored credentials.
reconnect() None Alias for connect(); discards the old connection object.
ping() bool Pings the server with reconnect=True. Called automatically before every statement.
close() None Closes the connection.
version() str Hard-coded library version string. Currently returns "0.1.9.2" and is not reliable — see Installation.

Closing the connection

Call close() when you are done. There is no context-manager support, so with mysql(...) as db: does not work — use try/finally if you need a guaranteed close.

db = mysql('localhost', 'root', 'secret', 'shop')

try:
    users = db.select('users')
finally:
    db.close()

Next step

Insert your first record →