Python interface to MySQL databases implementing the Python Database API version 2.0 specification.
npx @tessl/cli install tessl/pypi-mysql-python@1.2.0A Python interface to MySQL databases implementing the Python Database API version 2.0 specification. MySQL-python provides thread-safe database connectivity with comprehensive functionality for connecting to, querying, and managing MySQL databases from Python applications.
pip install MySQL-pythonimport MySQLdbFor type constants and field types:
from MySQLdb import FIELD_TYPE
from MySQLdb.constants import CLIENT, CR, ER, FLAG, REFRESHFor specific functionality:
from MySQLdb import cursors, converters, timesimport MySQLdb
# Connect to database
db = MySQLdb.connect(
host="localhost",
user="username",
passwd="password",
db="database_name"
)
# Create cursor and execute query
cursor = db.cursor()
cursor.execute("SELECT * FROM users WHERE id = %s", (1,))
# Fetch results
result = cursor.fetchone()
print(result)
# Commit changes and close
db.commit()
cursor.close()
db.close()Using context managers:
import MySQLdb
# Connection automatically closed on exit
with MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test") as db:
with db.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM users")
count = cursor.fetchone()[0]
print(f"Total users: {count}")MySQL-python is built on a layered architecture:
The design provides both ease of use through the high-level interface and performance through the underlying C extension, making it suitable for both simple scripts and high-performance applications.
Core functionality for establishing and managing database connections, including connection configuration, transaction control, and connection lifecycle management.
def connect(host=None, user=None, passwd=None, db=None, port=3306, **kwargs):
"""Create database connection."""
class Connection:
def autocommit(self, on): ...
def begin(self): ...
def commit(self): ...
def rollback(self): ...
def cursor(self, cursorclass=None): ...
def close(self): ...Comprehensive cursor functionality for executing queries and fetching results, including multiple cursor types for different use cases (tuple/dictionary rows, stored/streaming results).
class Cursor:
def execute(self, query, args=None): ...
def executemany(self, query, args): ...
def fetchone(self): ...
def fetchmany(self, size=None): ...
def fetchall(self): ...
class DictCursor: ...
class SSCursor: ...
class SSDictCursor: ...Automatic conversion between Python and MySQL data types, including date/time handling, binary data, and custom type converters.
def Binary(x): ...
def DateFromTicks(ticks): ...
def TimeFromTicks(ticks): ...
def TimestampFromTicks(ticks): ...
# Type sets for DB API 2.0 compliance
STRING: DBAPISet
BINARY: DBAPISet
NUMBER: DBAPISet
DATE: DBAPISet
TIME: DBAPISet
TIMESTAMP: DBAPISetEssential string escaping functions for SQL injection prevention and utility functions for client information and debugging.
def escape(obj, mapping): ...
def escape_string(s): ...
def escape_dict(d, mapping): ...
def escape_sequence(seq, mapping): ...
def string_literal(obj): ...
def get_client_info(): ...
def debug(debug_string): ...
# Module attributes
NULL: object
version_info: tuple
__version__: str
__author__: strMySQL protocol constants, error codes, field types, and comprehensive exception hierarchy for robust error handling.
# Constants modules
CLIENT: module # Connection flags
CR: module # Client error codes
ER: module # MySQL error codes
FIELD_TYPE: module # Column type constants
FLAG: module # Column property flags
REFRESH: module # Refresh operation flags
# Exception hierarchy
class MySQLError(Exception): ...
class Error(MySQLError): ...
class DatabaseError(Error): ...
class OperationalError(DatabaseError): ...Direct access to MySQL C API functionality for advanced use cases requiring fine-grained control over database operations and performance optimization.
import _mysql
def connect(**kwargs): ...
def escape_string(s): ...
def get_client_info(): ...
def thread_safe(): ...
# Connection object methods from C extension
connection.affected_rows()
connection.insert_id()
connection.ping()