# pydoc > pymysql

---
type: CommandReference
command: pymysql
mode: pydoc
section: 
source: pydoc3
---

## Quick Reference
- `import pymysql` — import the library
- `conn = pymysql.connect(host='localhost', user='root', password='', database='test')` — connect to a database
- `cursor = conn.cursor()` — create a cursor to execute SQL
- `cursor.execute("SELECT VERSION()")` — execute a query
- `row = cursor.fetchone()` — fetch one result row
- `conn.commit()` — commit the current transaction
- `conn.rollback()` — roll back the current transaction
- `conn.close()` — close the connection

## Name
`pymysql` — a pure-Python MySQL client library.

## Synopsis
python
import pymysql
connection = pymysql.connect(
    host=None, user=None, password="", database=None,
    port=3306, unix_socket=None, charset="", autocommit=False, ...
)
The `connect()` function (aliased as `Connection`) returns a connection object conforming to [PEP 249](https://www.python.org/dev/peps/pep-0249/#connection-objects).

## Connection Parameters
- `host` — MySQL server hostname or IP
- `user` — login username
- `password` — login password (alias `passwd` deprecated)
- `database` — default database (alias `db` deprecated)
- `port` — TCP port (default: 3306)
- `unix_socket` — path to Unix socket (overrides TCP)
- `charset` — connection charset
- `collation` — collation name
- `sql_mode` — default SQL mode
- `autocommit` — autocommit mode (default: `False`)
- `connect_timeout` — timeout in seconds (default: 10)
- `read_timeout` — read timeout in seconds (default: `None`)
- `write_timeout` — write timeout in seconds (default: `None`)
- `bind_address` — local network interface for connection
- `cursorclass` — custom cursor class (default: `pymysql.cursors.Cursor`)
- `init_command` — SQL executed immediately after connection
- `read_default_file` — my.cnf path to read `[client]` section
- `read_default_group` — group in config file to read
- `conv` — custom type converter dictionary
- `use_unicode` — default to Unicode strings (default: `True`)
- `client_flag` — custom flags, see `pymysql.constants.CLIENT`
- `local_infile` — enable `LOAD DATA LOCAL` (default: `False`)
- `max_allowed_packet` — max packet size in bytes (default: 16MB)
- `defer_connect` — delay connection until `connect()` called (default: `False`)
- `auth_plugin_map` — dict of authentication plugin classes
- `server_public_key` — SHA256 authentication plugin public key
- `binary_prefix` — add `_binary` prefix to bytes/bytearray (default: `False`)
- SSL parameters: `ssl` (SSLContext or dict), `ssl_ca`, `ssl_cert`, `ssl_key`, `ssl_key_password`, `ssl_disabled`, `ssl_verify_cert`, `ssl_verify_identity`
- `compress` — not supported
- `named_pipe` — not supported

## Connection Methods
- `cursor(cursor=None)` — create a cursor; optional cursor type: `Cursor`, `SSCursor`, `DictCursor`, `SSDictCursor`
- `begin()` — start a transaction
- `commit()` — commit current transaction
- `rollback()` — roll back current transaction
- `close()` — send quit and close socket
- `ping(reconnect=False)` — check if server is alive (reconnect deprecated)
- `select_db(db)` — switch to database `db`
- `set_character_set(charset, collation=None)` — execute `SET NAMES` and update encoding
- `set_charset(charset)` — deprecated, use `set_character_set()`
- `show_warnings()` — send `SHOW WARNINGS`
- `autocommit(value)` — enable/disable autocommit
- `get_autocommit()` — return current autocommit mode
- `character_set_name()` — return current charset name
- `get_host_info()` / `get_proto_info()` / `get_server_info()` — server information
- `insert_id()` — last inserted row ID
- `affected_rows()` — number of affected rows from last query
- `thread_id()` — connection thread ID
- `kill(thread_id)` — kill a thread
- `escape(obj, mapping=None)` / `literal(obj)` — **internal use only**, escape values
- `escape_string(s)` — escape a string
- `query(sql, unbuffered=False)` — internal, called from Cursor
- `next_result(unbuffered=False)` — internal
- `write_packet(payload)` — internal
- `connect(sock=None)` — (re)connect; used with `defer_connect`
- `open` — read-only property, `True` if connection is open
- `__enter__` / `__exit__` — context manager support

## Cursor Classes
The default cursor is `pymysql.cursors.Cursor`. Other options:
- `SSCursor` — server-side cursor (unbuffered)
- `DictCursor` — returns rows as dictionaries
- `SSDictCursor` — server-side dictionary cursor

## Exception Classes
- `MySQLError` — base exception for MySQL operations
  - `Error` — base for all error exceptions (not warnings)
    - `DatabaseError` — database-related errors
      - `DataError` — data problems (division by zero, out of range, etc.)
      - `IntegrityError` — relational integrity (foreign key, duplicate key)
      - `InternalError` — internal database errors (invalid cursor, out of sync)
      - `NotSupportedError` — unsupported operation (rollback on non‑transactional)
      - `OperationalError` — operational issues (disconnect, data source not found)
      - `ProgrammingError` — programming errors (table not found, syntax error)
    - `InterfaceError` — database interface errors
  - `Warning` — important warnings (data truncation, etc.)

## Data Type Constants
Sets of `pymysql.constants.FIELD_TYPE` values:
- `BINARY` — {249, 250, 251, 252}
- `DATE` — {10, 14}
- `NUMBER` — {0, 1, 3, 4, 5, 8, 9, 13}
- `STRING` — {253, 254, 247}
- `TIME` — {11}
- `TIMESTAMP` — {12, 7}
- `ROWID` — empty set
- `NULL` — string `'NULL'`

## Functions
- `Binary(x)` — return `x` as a binary type
- `DateFromTicks(ticks)` — return a date from ticks
- `TimeFromTicks(ticks)` — return a time from ticks
- `TimestampFromTicks(ticks)` — return a datetime from ticks
- `get_client_info()` — return client version string
- `install_as_MySQLdb()` — monkey-patch so that `import MySQLdb` uses PyMySQL

## Version
- `pymysql.version_info` — `(2, 2, 8, 'final', 1)`
- API level: `2.0`
- Parameter style: `pyformat`
- Thread safety: `1` (threads may share the module, but not connections)

## See Also
- [PEP 249 – Python Database API Specification v2.0](https://www.python.org/dev/peps/pep-0249/)
- [PyMySQL GitHub repository](https://github.com/PyMySQL/PyMySQL)