MySQL driver written in Python providing comprehensive database connectivity with both traditional SQL and modern document operations
—
Core connection functionality providing MySQL database connectivity with support for connection pooling, failover configurations, SSL/TLS encryption, and various authentication methods.
Creates a standard MySQL connection using pure Python implementation or optional C extension.
def connect(**config):
"""
Create a MySQL connection.
Parameters:
- user (str): MySQL username
- password (str): MySQL password
- host (str): MySQL server hostname (default: 'localhost')
- port (int): MySQL server port (default: 3306)
- database (str): Database name to connect to
- charset (str): Character set for the connection (default: 'utf8')
- use_pure (bool): Use pure Python implementation (default: True)
- ssl_disabled (bool): Disable SSL/TLS (default: False)
- autocommit (bool): Enable autocommit mode (default: False)
- time_zone (str): Session time zone
- connect_timeout (int): Connection timeout in seconds
- read_timeout (int): Read timeout in seconds
- write_timeout (int): Write timeout in seconds
- compress (bool): Enable connection compression
- unix_socket (str): Unix socket file path
- auth_plugin (str): Authentication plugin name
- collation (str): Connection collation
- sql_mode (str): SQL mode for the session
- init_command (str): Command to execute on connection
- use_unicode (bool): Return Unicode strings (default: True)
Returns:
MySQLConnection or CMySQLConnection: Database connection object
Raises:
Error: Connection failed or invalid parameters
"""Usage Example:
import mysql.connector
# Basic connection
connection = mysql.connector.connect(
user='myuser',
password='mypassword',
host='localhost',
database='mydatabase'
)
# Connection with SSL
connection = mysql.connector.connect(
user='myuser',
password='mypassword',
host='myserver.com',
database='mydatabase',
ssl_cert='/path/to/client-cert.pem',
ssl_key='/path/to/client-key.pem',
ssl_ca='/path/to/ca-cert.pem'
)Core connection implementations providing database connectivity and transaction management.
class MySQLConnection:
"""
Pure Python MySQL connection implementation.
Provides complete MySQL protocol implementation without external dependencies.
Supports all MySQL features including prepared statements, multiple result sets,
and comprehensive error handling.
"""
def __init__(self, **config):
"""Initialize connection with configuration parameters"""
def connect(self, **config):
"""Establish connection to MySQL server"""
def close(self):
"""Close the connection to MySQL server"""
def commit(self):
"""Commit current transaction"""
def rollback(self):
"""Rollback current transaction"""
def cursor(self, buffered=None, raw=None, prepared=None,
cursor_class=None, dictionary=None, named_tuple=None):
"""
Create a cursor for executing SQL statements.
Parameters:
- buffered (bool): Buffer all results immediately
- raw (bool): Return raw data without conversion
- prepared (bool): Use prepared statements
- cursor_class: Custom cursor class
- dictionary (bool): Return rows as dictionaries
- named_tuple (bool): Return rows as named tuples
Returns:
MySQLCursor: Cursor object for SQL operations
"""
def start_transaction(self, consistent_snapshot=False, isolation_level=None, readonly=None):
"""
Start a transaction.
Parameters:
- consistent_snapshot (bool): Use consistent snapshot
- isolation_level (str): Transaction isolation level
- readonly (bool): Read-only transaction
"""
def in_transaction(self):
"""Check if connection is in a transaction"""
def autocommit(self, value):
"""Set autocommit mode"""
def get_server_info(self):
"""Get MySQL server version information"""
def get_server_version(self):
"""Get MySQL server version as tuple"""
def ping(self, reconnect=True, attempts=1, delay=0):
"""
Ping the MySQL server.
Parameters:
- reconnect (bool): Attempt to reconnect if connection lost
- attempts (int): Number of ping attempts
- delay (int): Delay between attempts
"""
def reset_session(self, user_variables=None, session_variables=None):
"""Reset session state"""
def set_charset_collation(self, charset=None, collation=None):
"""Set character set and collation"""
class CMySQLConnection(MySQLConnection):
"""
C extension-based MySQL connection (optional).
Provides better performance through C implementation while maintaining
the same interface as MySQLConnection. Available only when C extension
is compiled and installed.
"""Manages pools of database connections for improved performance and resource utilization.
class MySQLConnectionPool:
"""
Connection pool for managing multiple MySQL connections.
Provides automatic connection lifecycle management, connection reuse,
and configurable pool sizing for optimal resource utilization.
"""
def __init__(self, pool_size=5, pool_name=None, pool_reset_session=True, **config):
"""
Initialize connection pool.
Parameters:
- pool_size (int): Maximum number of connections in pool (default: 5)
- pool_name (str): Unique name for the pool
- pool_reset_session (bool): Reset session variables on connection return
- **config: Connection configuration parameters
"""
def get_connection(self):
"""
Get a connection from the pool.
Returns:
PooledMySQLConnection: Pooled connection wrapper
Raises:
PoolError: No connections available
"""
def add_connection(self, cnx=None):
"""Add a connection to the pool"""
def set_config(**config):
"""Update pool configuration"""
class PooledMySQLConnection:
"""
Wrapper for pooled MySQL connections.
Provides the same interface as MySQLConnection while managing
automatic return to pool when connection is closed.
"""
def close(self):
"""Return connection to pool instead of closing"""
def config(self, **kwargs):
"""Configure the pooled connection"""
def generate_pool_name(**config):
"""
Generate a unique pool name based on connection configuration.
Parameters:
- **config: Connection configuration parameters
Returns:
str: Generated pool name
"""Usage Example:
import mysql.connector
# Create connection pool
config = {
'user': 'myuser',
'password': 'mypassword',
'host': 'localhost',
'database': 'mydatabase',
'pool_name': 'mypool',
'pool_size': 10
}
# Get pooled connection
connection = mysql.connector.connect(**config)
cursor = connection.cursor()
# Use connection normally
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
# Connection automatically returns to pool when closed
cursor.close()
connection.close()Automatic failover support for high availability MySQL configurations.
def connect(failover=None, **config):
"""
Create connection with failover support.
Parameters:
- failover (list): List of failover server configurations
- **config: Primary connection configuration
Returns:
MySQLConnection: Connection to available server
Raises:
InterfaceError: No servers available
"""Usage Example:
import mysql.connector
# Connection with failover servers
failover_config = {
'user': 'myuser',
'password': 'mypassword',
'database': 'mydatabase',
'failover': [
{'host': 'primary.mysql.com', 'port': 3306},
{'host': 'secondary.mysql.com', 'port': 3306},
{'host': 'tertiary.mysql.com', 'port': 3306}
]
}
connection = mysql.connector.connect(**failover_config)Read MySQL configuration from option files (my.cnf, my.ini).
def read_option_files(**config):
"""
Read MySQL option files and merge with provided configuration.
Parameters:
- option_files (list): List of option file paths to read
- option_groups (list): Option groups to read from files
- **config: Additional configuration parameters
Returns:
dict: Merged configuration from files and parameters
"""Usage Example:
import mysql.connector
# Connect using option files
connection = mysql.connector.connect(
option_files=['/etc/mysql/my.cnf', '~/.my.cnf'],
option_groups=['client', 'mysql']
)ConnectionPoolConfig = {
'pool_name': str,
'pool_size': int,
'pool_reset_session': bool
}
FailoverConfig = {
'failover': list[dict[str, any]]
}
SSLConfig = {
'ssl_disabled': bool,
'ssl_cert': str,
'ssl_key': str,
'ssl_ca': str,
'ssl_capath': str,
'ssl_cipher': str,
'ssl_verify_cert': bool,
'ssl_verify_identity': bool
}Install with Tessl CLI
npx tessl i tessl/pypi-mysql-connector