A self-contained Python driver for communicating with MySQL servers, using an API that is compliant with the Python Database API Specification v2.0 (PEP 249).
—
Low-level utilities, configuration management, platform detection, and advanced functionality for specialized use cases and system integration.
def intread(buf: bytes) -> int:
"""
Read integer from buffer using MySQL protocol format.
Args:
buf: Bytes buffer containing integer
Returns:
Integer value read from buffer
"""
pass
def int1store(value: int) -> bytes:
"""
Pack integer into 1-byte buffer.
Args:
value: Integer value (0-255)
Returns:
1-byte buffer containing packed integer
"""
pass
def int2store(value: int) -> bytes:
"""
Pack integer into 2-byte buffer (little-endian).
Args:
value: Integer value (0-65535)
Returns:
2-byte buffer containing packed integer
"""
pass
def int3store(value: int) -> bytes:
"""
Pack integer into 3-byte buffer (little-endian).
Args:
value: Integer value (0-16777215)
Returns:
3-byte buffer containing packed integer
"""
pass
def int4store(value: int) -> bytes:
"""
Pack integer into 4-byte buffer (little-endian).
Args:
value: Integer value (0-4294967295)
Returns:
4-byte buffer containing packed integer
"""
pass
def int8store(value: int) -> bytes:
"""
Pack integer into 8-byte buffer (little-endian).
Args:
value: Integer value (0-18446744073709551615)
Returns:
8-byte buffer containing packed integer
"""
pass
def intstore(value: int) -> bytes:
"""
Pack integer into variable-length buffer.
Args:
value: Integer value
Returns:
Variable-length buffer containing packed integer
"""
pass
def lc_int(value: int) -> bytes:
"""
Pack integer using length-coded format.
Args:
value: Integer value
Returns:
Length-coded buffer containing integer
"""
passdef read_bytes(buf: bytes, size: int) -> Tuple[bytes, int]:
"""
Read specified number of bytes from buffer.
Args:
buf: Source buffer
size: Number of bytes to read
Returns:
Tuple of (read_bytes, new_position)
"""
pass
def read_lc_string(buf: bytes) -> Tuple[bytes, int]:
"""
Read length-coded string from buffer.
Args:
buf: Buffer containing length-coded string
Returns:
Tuple of (string_bytes, new_position)
"""
pass
def read_string(buf: bytes, end: bytes, charset: str = 'utf8') -> str:
"""
Read string from buffer until end marker.
Args:
buf: Buffer containing string data
end: End marker bytes
charset: Character encoding (default: 'utf8')
Returns:
Decoded string
"""
pass
def read_int(buf: bytes, size: int) -> Tuple[int, int]:
"""
Read integer from buffer.
Args:
buf: Buffer containing integer data
size: Size of integer in bytes (1, 2, 3, 4, or 8)
Returns:
Tuple of (integer_value, new_position)
"""
pass
def read_lc_int(buf: bytes) -> Tuple[int, int]:
"""
Read length-coded integer from buffer.
Args:
buf: Buffer containing length-coded integer
Returns:
Tuple of (integer_value, new_position)
"""
passdef get_platform() -> str:
"""
Get platform information string.
Returns:
Platform identifier string (e.g., 'Linux-x86_64', 'Windows-AMD64')
"""
pass
def linux_distribution() -> Tuple[str, str, str]:
"""
Get Linux distribution information.
Returns:
Tuple of (distribution_name, version, codename)
Returns empty tuple on non-Linux platforms
"""
passdef import_object(fullpath: str) -> Any:
"""
Import object from module path.
Args:
fullpath: Full module path (e.g., 'package.module.ClassName')
Returns:
Imported object (class, function, etc.)
Raises:
ImportError: If module or object cannot be imported
"""
passdef normalize_unicode_string(string: str) -> str:
"""
Normalize Unicode string for security and consistency.
Args:
string: Input Unicode string
Returns:
Normalized Unicode string
"""
pass
def validate_normalized_unicode_string(string: str) -> bool:
"""
Validate that Unicode string is properly normalized.
Args:
string: Unicode string to validate
Returns:
True if string is normalized, False otherwise
"""
passclass MySQLOptionsParser:
"""
MySQL option file parser for my.cnf files.
Handles MySQL configuration file parsing and option extraction.
"""
def __init__(self) -> None:
"""Initialize option file parser."""
pass
def read_option_files(self, files: List[str]) -> Dict[str, Dict[str, str]]:
"""
Read MySQL option files and extract configuration.
Args:
files: List of option file paths to read
Returns:
Dictionary with sections and their options
"""
pass
def read_groups(self, groups: List[str]) -> Dict[str, str]:
"""
Read specific option groups from files.
Args:
groups: List of option group names to read
Returns:
Dictionary with merged options from specified groups
"""
pass
def get_groups(self) -> List[str]:
"""
Get list of available option groups.
Returns:
List of option group names found in files
"""
pass
def read_option_files(files: List[str]) -> Dict[str, Dict[str, str]]:
"""
Convenience function to read MySQL option files.
Args:
files: List of option file paths
Returns:
Dictionary with parsed options organized by section
"""
passclass MySQLSocket:
"""
Base socket class for MySQL connections.
Provides common socket functionality for different connection types.
"""
def __init__(self) -> None:
"""Initialize base socket."""
pass
def open_connection(self) -> None:
"""Open socket connection."""
pass
def close_connection(self) -> None:
"""Close socket connection."""
pass
def send(self, data: bytes) -> int:
"""Send data through socket."""
pass
def recv(self, size: int) -> bytes:
"""Receive data from socket."""
pass
def set_connection_timeout(self, timeout: int) -> None:
"""Set connection timeout in seconds."""
pass
class MySQLTCPSocket(MySQLSocket):
"""
TCP socket implementation for MySQL connections.
Handles TCP/IP connections to MySQL server.
"""
def __init__(self, host: str = 'localhost', port: int = 3306) -> None:
"""
Initialize TCP socket.
Args:
host: MySQL server hostname
port: MySQL server port number
"""
pass
class MySQLUnixSocket(MySQLSocket):
"""
Unix socket implementation for MySQL connections.
Handles Unix domain socket connections to local MySQL server.
"""
def __init__(self, unix_socket: str) -> None:
"""
Initialize Unix socket.
Args:
unix_socket: Path to MySQL Unix socket file
"""
passclass MySQLLogger:
"""
MySQL Connector logging utilities.
Provides structured logging for MySQL operations.
"""
def __init__(self, name: str = 'mysql.connector') -> None:
"""
Initialize MySQL logger.
Args:
name: Logger name
"""
pass
def log_connection(self, host: str, user: str, database: str) -> None:
"""Log connection attempt."""
pass
def log_query(self, query: str, params: Optional[Tuple] = None) -> None:
"""Log SQL query execution."""
pass
def log_error(self, error: Exception, context: str = '') -> None:
"""Log error with context."""
passclass MySQLProtocol:
"""
MySQL client/server protocol implementation.
Handles low-level MySQL protocol communication.
"""
def __init__(self) -> None:
"""Initialize protocol handler."""
pass
def parse_handshake(self, packet: bytes) -> Dict[str, Any]:
"""
Parse MySQL handshake packet.
Args:
packet: Handshake packet bytes
Returns:
Dictionary with handshake information
"""
pass
def make_auth_response(self, handshake: Dict[str, Any], user: str, password: str, database: str) -> bytes:
"""
Create authentication response packet.
Args:
handshake: Handshake information
user: Username
password: Password
database: Database name
Returns:
Authentication response packet bytes
"""
pass
def parse_ok_packet(self, packet: bytes) -> Dict[str, Any]:
"""
Parse MySQL OK packet.
Args:
packet: OK packet bytes
Returns:
Dictionary with OK packet information
"""
pass
def parse_error_packet(self, packet: bytes) -> Dict[str, Any]:
"""
Parse MySQL error packet.
Args:
packet: Error packet bytes
Returns:
Dictionary with error information
"""
pass
def parse_result_set_header(self, packet: bytes) -> int:
"""
Parse result set header packet.
Args:
packet: Result set header packet bytes
Returns:
Number of columns in result set
"""
pass
def parse_column_definition(self, packet: bytes) -> Dict[str, Any]:
"""
Parse column definition packet.
Args:
packet: Column definition packet bytes
Returns:
Dictionary with column information
"""
pass
def parse_row_data(self, packet: bytes, columns: int) -> List[bytes]:
"""
Parse row data packet.
Args:
packet: Row data packet bytes
columns: Number of columns
Returns:
List of column values as bytes
"""
passfrom mysql.connector.utils import int1store, int2store, int4store, intread
# Pack integers for protocol communication
one_byte = int1store(255) # b'\xff'
two_bytes = int2store(65535) # b'\xff\xff' (little-endian)
four_bytes = int4store(4294967295) # b'\xff\xff\xff\xff'
print(f"1-byte: {one_byte.hex()}")
print(f"2-byte: {two_bytes.hex()}")
print(f"4-byte: {four_bytes.hex()}")
# Read integer from buffer
buffer = b'\x42\x00\x00\x00' # 66 in little-endian 4-byte format
value = intread(buffer)
print(f"Read value: {value}")from mysql.connector.utils import read_lc_string, read_string
# Example MySQL protocol buffer with length-coded string
# Format: [length][string_data]
buffer = b'\x0bHello World' # Length 11, followed by "Hello World"
string_data, new_pos = read_lc_string(buffer)
print(f"Read string: {string_data.decode('utf-8')}")
print(f"New position: {new_pos}")
# Read null-terminated string
null_term_buffer = b'Hello World\x00more data'
string_value = read_string(null_term_buffer, b'\x00', 'utf-8')
print(f"Null-terminated string: {string_value}")from mysql.connector.utils import get_platform, linux_distribution
# Get platform information
platform = get_platform()
print(f"Platform: {platform}")
# Get Linux distribution info (if on Linux)
try:
dist_info = linux_distribution()
if dist_info:
name, version, codename = dist_info
print(f"Linux Distribution: {name} {version} ({codename})")
except:
print("Not running on Linux or distribution info unavailable")from mysql.connector.utils import import_object
# Import specific class or function
try:
MySQLConnection = import_object('mysql.connector.connection.MySQLConnection')
print(f"Imported class: {MySQLConnection}")
# Import authentication plugin
sha2_plugin = import_object('mysql.connector.plugins.caching_sha2_password')
print(f"Imported plugin: {sha2_plugin}")
except ImportError as err:
print(f"Import failed: {err}")from mysql.connector.optionfiles import MySQLOptionsParser, read_option_files
# Read MySQL configuration files
option_files = [
'/etc/mysql/my.cnf',
'/etc/my.cnf',
'~/.my.cnf'
]
try:
# Using parser class
parser = MySQLOptionsParser()
options = parser.read_option_files([f for f in option_files if os.path.exists(f)])
print("MySQL Configuration:")
for section, section_options in options.items():
print(f"[{section}]")
for key, value in section_options.items():
print(f" {key} = {value}")
print()
# Read specific groups
client_options = parser.read_groups(['client', 'mysql_connector_python'])
print(f"Client options: {client_options}")
except Exception as err:
print(f"Failed to read option files: {err}")from mysql.connector.utils import normalize_unicode_string, validate_normalized_unicode_string
# Unicode normalization for security
user_input = "café" # May contain different Unicode representations
normalized = normalize_unicode_string(user_input)
print(f"Original: {user_input}")
print(f"Normalized: {normalized}")
print(f"Is normalized: {validate_normalized_unicode_string(normalized)}")
# Validate user input before database operations
def safe_insert_user(name: str, email: str):
"""Safely insert user with Unicode normalization."""
if not validate_normalized_unicode_string(name):
name = normalize_unicode_string(name)
if not validate_normalized_unicode_string(email):
email = normalize_unicode_string(email)
# Proceed with database insert
print(f"Inserting user: {name}, {email}")
safe_insert_user("José", "josé@example.com")import mysql.connector
from mysql.connector.network import MySQLTCPSocket
# Custom socket configuration
class CustomMySQLSocket(MySQLTCPSocket):
"""Custom socket with additional logging."""
def send(self, data: bytes) -> int:
print(f"Sending {len(data)} bytes")
return super().send(data)
def recv(self, size: int) -> bytes:
data = super().recv(size)
print(f"Received {len(data)} bytes")
return data
# Use custom socket (conceptual - actual integration may vary)
# This demonstrates how you might extend socket functionalityfrom mysql.connector.protocol import MySQLProtocol
# Analyze MySQL protocol packets (conceptual example)
protocol = MySQLProtocol()
# Example handshake packet (would come from actual MySQL server)
handshake_packet = b'\x0a8.0.32\x00...' # Truncated for example
try:
handshake_info = protocol.parse_handshake(handshake_packet)
print(f"Server version: {handshake_info.get('server_version')}")
print(f"Thread ID: {handshake_info.get('thread_id')}")
print(f"Server capabilities: {handshake_info.get('server_capabilities')}")
except Exception as err:
print(f"Failed to parse handshake: {err}")import mysql.connector
from mysql.connector.utils import get_platform
import logging
# Configure detailed debugging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('mysql.connector')
def debug_connection(config: dict):
"""Create connection with detailed debugging information."""
print(f"Platform: {get_platform()}")
print(f"MySQL Connector version: {mysql.connector.__version__}")
try:
connection = mysql.connector.connect(**config)
# Connection details
print(f"Connected to: {connection.server_host}:{connection.server_port}")
print(f"Server version: {connection.server_version}")
print(f"Connection ID: {connection.connection_id}")
print(f"Character set: {connection.charset}")
print(f"Collation: {connection.collation}")
print(f"SQL mode: {connection.sql_mode}")
print(f"Autocommit: {connection.autocommit}")
print(f"In transaction: {connection.in_transaction}")
# Server status
cursor = connection.cursor()
cursor.execute("SHOW STATUS LIKE 'Threads_connected'")
result = cursor.fetchone()
print(f"Server threads connected: {result[1]}")
# SSL information if enabled
cursor.execute("SHOW STATUS LIKE 'Ssl_cipher'")
result = cursor.fetchone()
if result and result[1]:
print(f"SSL cipher: {result[1]}")
cursor.close()
connection.close()
except mysql.connector.Error as err:
print(f"Connection debug failed: {err}")
logger.error(f"Connection error details: {err}")
# Debug connection
config = {
'host': 'localhost',
'user': 'myuser',
'password': 'mypassword',
'database': 'mydatabase'
}
debug_connection(config)import time
import mysql.connector
from mysql.connector.utils import get_platform
def benchmark_connection_methods():
"""Compare performance of different connection methods."""
config = {
'host': 'localhost',
'user': 'myuser',
'password': 'mypassword',
'database': 'mydatabase'
}
methods = [
('Pure Python', {'use_pure': True}),
('C Extension', {'use_pure': False}),
('Compressed', {'compress': True, 'use_pure': False}),
('Buffered', {'buffered': True, 'use_pure': False})
]
for method_name, method_config in methods:
test_config = {**config, **method_config}
try:
start_time = time.time()
connection = mysql.connector.connect(**test_config)
cursor = connection.cursor()
# Perform test operations
for i in range(100):
cursor.execute("SELECT %s", (i,))
cursor.fetchone()
cursor.close()
connection.close()
end_time = time.time()
duration = end_time - start_time
print(f"{method_name}: {duration:.3f} seconds")
except mysql.connector.Error as err:
print(f"{method_name}: Failed - {err}")
print(f"Running benchmarks on {get_platform()}")
benchmark_connection_methods()Install with Tessl CLI
npx tessl i tessl/pypi-mysql-connector-python