CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mysql-connector-python

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).

Pending
Overview
Eval results
Files

connection.mddocs/

Connection Management

Establish and manage database connections to MySQL servers with comprehensive configuration options, SSL/TLS support, and optional C extension optimization.

Imports

from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union
from mysql.connector import MySQLConnection, PooledMySQLConnection
from mysql.connector.cursor import MySQLCursor

Core Connection Functions

def connect(**kwargs) -> Union[MySQLConnection, PooledMySQLConnection]:
    """
    Create connection to MySQL server.
    
    Returns PooledMySQLConnection when pool parameters are provided,
    otherwise returns MySQLConnection or CMySQLConnection (if C extension available).
    """
    pass

# Alias for connect function
Connect = connect

Connection Classes

MySQLConnection

class MySQLConnection:
    """
    Main synchronous connection class implementing DB-API 2.0.
    Provides standard MySQL connectivity with transaction support.
    """
    
    def __init__(self, **kwargs) -> None:
        """Initialize connection with configuration parameters."""
        pass
    
    def connect(self, **kwargs) -> None:
        """Establish connection to MySQL server."""
        pass
    
    def disconnect(self) -> None:
        """Close connection to MySQL server."""
        pass
    
    def close(self) -> None:
        """Close connection (alias for disconnect)."""
        pass
    
    def is_connected(self) -> bool:
        """Check if connection is active."""
        pass
    
    def ping(self, reconnect: bool = False, attempts: int = 1, delay: int = 0) -> None:
        """Test connection to server, optionally reconnecting."""
        pass
    
    def reconnect(self, attempts: int = 1, delay: int = 0) -> None:
        """Reconnect to MySQL server."""
        pass
    
    def cursor(self, 
               buffered: Optional[bool] = None,
               raw: Optional[bool] = None,
               prepared: Optional[bool] = None,
               cursor_class: Optional[Type] = None,
               dictionary: Optional[bool] = None,
               named_tuple: Optional[bool] = None) -> MySQLCursor:
        """Create cursor for executing SQL statements."""
        pass
    
    def commit(self) -> None:
        """Commit current transaction."""
        pass
    
    def rollback(self) -> None:
        """Rollback current transaction."""
        pass
    
    def start_transaction(self, 
                         consistent_snapshot: bool = False,
                         isolation_level: Optional[str] = None,
                         readonly: Optional[bool] = None) -> None:
        """Start new transaction with optional configuration."""
        pass
    
    @property
    def autocommit(self) -> bool:
        """Get autocommit mode status."""
        pass
    
    @autocommit.setter
    def autocommit(self, value: bool) -> None:
        """Set autocommit mode."""
        pass
    
    @property
    def database(self) -> str:
        """Get current database name."""
        pass
    
    @database.setter 
    def database(self, value: str) -> None:
        """Change current database."""
        pass
    
    @property
    def server_version(self) -> Tuple[int, int, int]:
        """Get MySQL server version tuple."""
        pass
    
    @property
    def connection_id(self) -> int:
        """Get MySQL connection ID."""
        pass
    
    @property
    def charset(self) -> str:
        """Get connection character set."""
        pass
    
    @charset.setter
    def charset(self, value: str) -> None:
        """Set connection character set."""
        pass
    
    @property
    def collation(self) -> str:
        """Get connection collation."""
        pass
    
    @collation.setter
    def collation(self, value: str) -> None:
        """Set connection collation."""
        pass
    
    @property
    def sql_mode(self) -> str:
        """Get SQL mode."""
        pass
    
    @sql_mode.setter
    def sql_mode(self, value: str) -> None:
        """Set SQL mode."""
        pass
    
    @property
    def time_zone(self) -> str:
        """Get connection time zone."""
        pass
    
    @time_zone.setter
    def time_zone(self, value: str) -> None:
        """Set connection time zone."""
        pass
    
    def cmd_query(self, query: Union[str, bytes]) -> Dict:
        """Execute query and return raw result."""
        pass
    
    def cmd_quit(self) -> bytes:
        """Send quit command to server."""
        pass
    
    def cmd_init_db(self, database: str) -> bytes:
        """Send init_db command to change database."""
        pass
    
    def cmd_refresh(self, options: int) -> bytes:
        """Send refresh command with specified options."""
        pass
    
    def cmd_statistics(self) -> Dict:
        """Get server statistics."""
        pass
    
    def cmd_process_info(self) -> Tuple:
        """Get server process information."""
        pass
    
    def cmd_process_kill(self, mysql_pid: int) -> bytes:
        """Kill MySQL process by ID.""" 
        pass
    
    def cmd_debug(self) -> bytes:
        """Send debug command to server."""
        pass
    
    def cmd_ping(self) -> bytes:
        """Send ping command to server."""
        pass
    
    def cmd_change_user(self, username: str = '', password: str = '', database: str = '', charset: int = 33) -> bytes:
        """Change user authentication."""
        pass
    
    def cmd_stmt_prepare(self, statement: Union[str, bytes]) -> Dict:
        """Prepare SQL statement."""
        pass
    
    def cmd_stmt_execute(self, statement_id: int, data: Tuple = (), parameters: Tuple = (), flags: int = 0) -> Optional[Dict]:
        """Execute prepared statement."""
        pass
    
    def cmd_stmt_close(self, statement_id: int) -> bytes:
        """Close prepared statement."""
        pass
    
    def cmd_stmt_reset(self, statement_id: int) -> bytes:
        """Reset prepared statement."""
        pass
    
    def reset_session(self, user_variables: Optional[Dict] = None, session_variables: Optional[Dict] = None) -> None:
        """Reset session to initial state."""
        pass
    
    def get_warnings(self, count: Optional[int] = None) -> List[Tuple]:
        """Get warning messages from last statement."""
        pass
    
    @property
    def warning_count(self) -> int:
        """Get warning count from last statement."""
        pass
    
    @property
    def info_msg(self) -> Optional[str]:
        """Get info message from last statement."""
        pass
    
    @property
    def field_count(self) -> int:
        """Get field count from last result."""
        pass
    
    @property
    def insert_id(self) -> int:
        """Get auto-generated ID from last INSERT."""
        pass
    
    @property
    def affected_rows(self) -> int:
        """Get affected row count from last statement."""
        pass
    
    @property
    def in_transaction(self) -> bool:
        """Check if connection is in transaction."""
        pass
    
    # Query Attributes API
    @property
    def query_attrs(self) -> List[Tuple[str, Any]]:
        """Get query attributes list."""
        pass
    
    def query_attrs_append(self, value: Tuple[str, Any]) -> None:
        """
        Add element to query attributes list.
        
        If an element with the same name exists, it will be replaced.
        """
        pass
    
    def query_attrs_remove(self, name: str) -> Any:
        """
        Remove element by name from query attributes list.
        
        Returns the corresponding value if found, None otherwise.
        """
        pass
    
    def query_attrs_clear(self) -> None:
        """Clear all query attributes."""
        pass
    
    # Server Information API
    def get_server_info(self) -> Optional[str]:
        """Get original MySQL server version information string."""
        pass
    
    def get_server_version(self) -> Optional[Tuple[int, ...]]:
        """Get MySQL server version as tuple of integers."""
        pass
    
    @property
    def server_info(self) -> Optional[str]:
        """Get original MySQL server version information string."""
        pass
    
    # Security and State API
    @property
    def is_secure(self) -> bool:
        """Check if connection uses SSL/TLS or Unix socket security."""
        pass
    
    @property
    def have_next_result(self) -> bool:
        """Check if there are additional result sets available."""
        pass
    
    def set_client_flags(self, flags: Union[int, Sequence[int]]) -> int:
        """
        Set client capability flags.
        
        Args:
            flags: Integer or sequence of ClientFlag values
            
        Returns:
            Current client flags value
        """
        pass
    
    def get_self(self) -> 'MySQLConnection':
        """Return self for weakref.proxy support."""
        pass
    
    def __enter__(self) -> 'MySQLConnection':
        """Context manager entry."""
        pass
    
    def __exit__(self, exc_type, exc_val, exc_tb) -> None:
        """Context manager exit with automatic cleanup."""
        pass

CMySQLConnection

class CMySQLConnection(MySQLConnection):
    """
    C Extension optimized connection class.
    Available when C extension is installed and HAVE_CEXT is True.
    Provides same interface as MySQLConnection with improved performance.
    """
    pass

Connection Parameters

Basic Parameters

# Essential connection parameters
connection_config = {
    'host': str,        # MySQL server host (default: 'localhost')
    'port': int,        # MySQL server port (default: 3306) 
    'user': str,        # Username for authentication
    'password': str,    # Password for authentication
    'database': str,    # Database name to connect to
    'unix_socket': str, # Unix socket path (alternative to host/port)
}

Character Set and Encoding

charset_config = {
    'charset': str,        # Connection character set (default: 'utf8mb4')
    'collation': str,      # Connection collation  
    'use_unicode': bool,   # Enable Unicode support (default: True)
}

Connection Behavior

behavior_config = {
    'autocommit': bool,           # Enable autocommit mode (default: False)
    'time_zone': str,             # Connection time zone
    'sql_mode': str,              # SQL mode settings
    'init_command': str,          # Command to run on connect
    'connect_timeout': int,       # Connection timeout in seconds (default: 10)
    'read_timeout': int,          # Read timeout in seconds
    'write_timeout': int,         # Write timeout in seconds
    'client_flags': List[int],    # MySQL client flags
    'compress': bool,             # Enable compression (default: False)
    'buffered': bool,             # Buffer results by default
    'raw': bool,                  # Return raw results by default
    'consume_results': bool,      # Consume unread results (default: False)
    'force_ipv6': bool,          # Force IPv6 usage
    'dsn': str,                  # Data source name string
}

SSL/TLS Configuration

ssl_config = {
    'ssl_disabled': bool,        # Disable SSL/TLS (default: False)
    'ssl_cert': str,            # Client certificate file path
    'ssl_key': str,             # Client private key file path
    'ssl_ca': str,              # Certificate authority file path
    'ssl_capath': str,          # Certificate authority directory path
    'ssl_cipher': str,          # SSL cipher specification
    'ssl_verify_cert': bool,    # Verify server certificate (default: False)
    'ssl_verify_identity': bool, # Verify server identity (default: False)
    'tls_versions': List[str],  # Allowed TLS versions
    'tls_ciphersuites': List[str], # Allowed TLS 1.3 cipher suites
}

Authentication Configuration

auth_config = {
    'auth_plugin': str,             # Authentication plugin name
    'auth_plugin_map': Dict[str, Type], # Plugin name to class mapping
    'password1': str,               # First factor password (MFA)
    'password2': str,               # Second factor password (MFA)  
    'password3': str,               # Third factor password (MFA)
    'oci_config_file': str,        # OCI config file path
    'oci_config_profile': str,     # OCI config profile name
    'authentication_kerberos_client_mode': int, # Kerberos mode
    'authentication_ldap_sasl_client_mode': int, # LDAP SASL mode
    'authentication_webauthn_client_mode': int,  # WebAuthn mode
}

Advanced Options

advanced_config = {
    'converter_class': Type,        # Custom converter class
    'converter_str_fallback': bool, # String conversion fallback
    'failover': List[Dict],        # Failover server configurations
    'option_files': List[str],     # MySQL option files to read
    'option_groups': List[str],    # Option file groups to read
    'allow_local_infile': bool,    # Allow LOAD DATA LOCAL INFILE
    'allow_local_infile_in_path': str, # Restrict LOCAL INFILE to path
    'use_pure': bool,              # Force pure Python implementation
    'get_warnings': bool,          # Automatically fetch warnings
    'raise_on_warnings': bool,     # Raise exceptions for warnings
    'collation': str,              # Connection collation
    'autocommit': bool,            # Autocommit transactions
    'prepared': bool,              # Use prepared statements by default
}

Usage Examples

Basic Connection

import mysql.connector

# Simple connection
connection = mysql.connector.connect(
    host='localhost',
    user='myuser',
    password='mypassword',
    database='mydatabase'
)

cursor = connection.cursor()
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print(f"MySQL version: {version[0]}")

cursor.close()
connection.close()

Connection with SSL

import mysql.connector

# SSL-enabled connection
connection = mysql.connector.connect(
    host='mysql.example.com',
    user='myuser', 
    password='mypassword',
    database='mydatabase',
    ssl_cert='/path/to/client-cert.pem',
    ssl_key='/path/to/client-key.pem',
    ssl_ca='/path/to/ca-cert.pem',
    ssl_verify_cert=True,
    ssl_verify_identity=True
)

Context Manager Usage

import mysql.connector

# Automatic connection cleanup
with mysql.connector.connect(
    host='localhost',
    user='myuser',
    password='mypassword', 
    database='mydatabase'
) as connection:
    cursor = connection.cursor()
    cursor.execute("SELECT COUNT(*) FROM users")
    count = cursor.fetchone()[0]
    print(f"User count: {count}")
    # Connection automatically closed

Connection with Configuration Dictionary

import mysql.connector

config = {
    'host': 'localhost',
    'port': 3306,
    'user': 'myuser',
    'password': 'mypassword',
    'database': 'mydatabase',
    'charset': 'utf8mb4',
    'collation': 'utf8mb4_unicode_ci',
    'autocommit': True,
    'connect_timeout': 30,
    'ssl_disabled': False,
    'ssl_verify_cert': True
}

connection = mysql.connector.connect(**config)

Checking Connection Status

import mysql.connector

connection = mysql.connector.connect(
    host='localhost',
    user='myuser',
    password='mypassword'
)

# Check connection status
if connection.is_connected():
    print("Connected to MySQL")
    print(f"Server version: {connection.server_version}")
    print(f"Connection ID: {connection.connection_id}")
    print(f"Current database: {connection.database}")
else:
    print("Not connected")

# Test connection with ping
try:
    connection.ping(reconnect=True)
    print("Connection is alive")
except mysql.connector.Error as err:
    print(f"Connection error: {err}")

connection.close()

Install with Tessl CLI

npx tessl i tessl/pypi-mysql-connector-python

docs

async.md

auth.md

connection.md

constants.md

cursors.md

errors.md

index.md

pooling.md

types.md

utilities.md

tile.json