CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mysql-python

Python interface to MySQL databases implementing the Python Database API version 2.0 specification.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

cursors.mddocs/

Cursor Operations

Comprehensive cursor functionality for executing SQL queries and fetching results, with multiple cursor types optimized for different use cases including tuple/dictionary rows and stored/streaming result handling.

Capabilities

Base Cursor Classes

Core cursor functionality providing the foundation for all cursor types.

class BaseCursor:
    """Base cursor class with common functionality for all cursor types."""
    
    def __init__(self, connection):
        """
        Initialize cursor with database connection.
        
        Parameters:
        - connection: Database connection object
        """
    
    def close(self):
        """Close the cursor and free associated resources."""
    
    def execute(self, query, args=None):
        """
        Execute a SQL statement.
        
        Parameters:
        - query (str): SQL query string with optional parameter placeholders
        - args (tuple/dict, optional): Parameters for query placeholders
        
        Returns:
        int: Number of affected rows
        """
    
    def executemany(self, query, args):
        """
        Execute a SQL statement multiple times with different parameters.
        
        Parameters:
        - query (str): SQL query string with parameter placeholders
        - args (sequence): Sequence of parameter tuples/dicts
        
        Returns:
        int: Number of affected rows for last execution
        """
    
    def callproc(self, procname, args=()):
        """
        Call a stored procedure.
        
        Parameters:
        - procname (str): Name of stored procedure
        - args (tuple): Parameters for stored procedure
        
        Returns:
        tuple: Modified parameter values
        """
    
    def fetchone(self):
        """
        Fetch the next row from query results.
        
        Returns:
        tuple/dict/None: Next row or None if no more rows
        """
    
    def fetchmany(self, size=None):
        """
        Fetch multiple rows from query results.
        
        Parameters:
        - size (int, optional): Number of rows to fetch (default: arraysize)
        
        Returns:
        list: List of rows (tuples or dicts)
        """
    
    def fetchall(self):
        """
        Fetch all remaining rows from query results.
        
        Returns:
        list: List of all remaining rows
        """
    
    def nextset(self):
        """
        Skip to next result set (for multiple result sets).
        
        Returns:
        bool: True if more result sets available, False otherwise
        """
    
    def setinputsizes(self, *args):
        """
        Set input parameter sizes (no-op for MySQL-python).
        
        Parameters:
        - args: Parameter size specifications (ignored)
        """
    
    def setoutputsizes(self, *args):
        """
        Set output column sizes (no-op for MySQL-python).
        
        Parameters:
        - args: Column size specifications (ignored)
        """
    
    def scroll(self, value, mode='relative'):
        """
        Scroll the cursor in the result set to a new position.
        
        Only available for stored result cursors (Cursor, DictCursor).
        Not supported by streaming cursors (SSCursor, SSDictCursor).
        
        Parameters:
        - value (int): Position offset or absolute position
        - mode (str): 'relative' (default) or 'absolute'
        """
    
    def __iter__(self):
        """
        Make cursor iterable for row-by-row processing.
        
        Returns:
        iterator: Cursor iterator
        """
    
    def __del__(self):
        """Destructor for automatic cursor cleanup."""

    # Cursor attributes
    arraysize: int        # Number of rows fetchmany() returns by default
    description: tuple    # Column descriptions for current result set
    lastrowid: int        # Row ID of last inserted row
    rowcount: int         # Number of rows affected/returned by last operation
    rownumber: int        # Current row position in result set
    connection: object    # Associated connection object
    messages: list        # List of messages/warnings from last operation
    description_flags: tuple  # Column flags for each field in result set
    _executed: str        # Last executed SQL statement
    errorhandler: function  # Custom error handler function
    _warnings: int        # Number of warnings from last operation
    _info: str           # Additional info from last operation

Cursor Mixins

Mixin classes that provide specialized behaviors for different cursor types.

class CursorStoreResultMixIn:
    """Mixin for cursors that store complete result sets in memory."""

class CursorUseResultMixIn:
    """Mixin for cursors that stream results from server (memory efficient)."""

class CursorTupleRowsMixIn:
    """Mixin for cursors that return rows as tuples."""

class CursorDictRowsMixIn:
    """Mixin for cursors that return rows as dictionaries with column names as keys."""

class CursorOldDictRowsMixIn:
    """Mixin for cursors that return rows as old-style dictionaries."""

Standard Cursor Types

Pre-configured cursor classes combining mixins for common use cases.

class Cursor(CursorStoreResultMixIn, CursorTupleRowsMixIn, BaseCursor):
    """
    Standard cursor returning rows as tuples with results stored in memory.
    Default cursor type providing best compatibility and performance for most use cases.
    """

class DictCursor(CursorStoreResultMixIn, CursorDictRowsMixIn, BaseCursor):
    """
    Dictionary cursor returning rows as dictionaries with column names as keys.
    Results stored in memory. Useful for applications that need named column access.
    """

class SSCursor(CursorUseResultMixIn, CursorTupleRowsMixIn, BaseCursor):
    """
    Server-side cursor returning rows as tuples with streaming results.
    Memory efficient for large result sets but requires careful handling.
    """

class SSDictCursor(CursorUseResultMixIn, CursorDictRowsMixIn, BaseCursor):
    """
    Server-side dictionary cursor with streaming results and named column access.
    Combines memory efficiency with convenient dictionary-style row access.
    """

Usage Examples

Basic Query Execution

import MySQLdb

db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")
cursor = db.cursor()

# Execute simple query
cursor.execute("SELECT id, name, email FROM users WHERE active = %s", (1,))

# Fetch results
results = cursor.fetchall()
for row in results:
    user_id, name, email = row
    print(f"User {user_id}: {name} ({email})")

cursor.close()
db.close()

Dictionary Cursor Usage

import MySQLdb

db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")

# Use dictionary cursor for named column access
cursor = db.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT id, name, email FROM users WHERE active = %s", (1,))

results = cursor.fetchall()
for row in results:
    print(f"User {row['id']}: {row['name']} ({row['email']})")

cursor.close()
db.close()

Server-Side Cursor for Large Results

import MySQLdb

db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")

# Use server-side cursor for memory efficiency with large result sets
cursor = db.cursor(MySQLdb.cursors.SSCursor)
cursor.execute("SELECT * FROM large_table")

# Process results one row at a time
for row in cursor:
    process_row(row)  # Process without loading all rows into memory

cursor.close()
db.close()

Batch Operations with executemany

import MySQLdb

db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")
cursor = db.cursor()

# Insert multiple rows efficiently
users_data = [
    ("John Doe", "john@example.com"),
    ("Jane Smith", "jane@example.com"), 
    ("Bob Wilson", "bob@example.com")
]

cursor.executemany(
    "INSERT INTO users (name, email) VALUES (%s, %s)",
    users_data
)

db.commit()
print(f"Inserted {cursor.rowcount} users")

cursor.close()
db.close()

Stored Procedure Calls

import MySQLdb

db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")
cursor = db.cursor()

# Call stored procedure
args = (100, 0)  # input parameter, output parameter
result = cursor.callproc("calculate_tax", args)
print(f"Tax calculation result: {result}")

# Fetch any result sets returned by procedure
if cursor.description:
    results = cursor.fetchall()
    for row in results:
        print(row)

cursor.close()
db.close()

Iterator Pattern for Row Processing

import MySQLdb

db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")
cursor = db.cursor()

cursor.execute("SELECT id, name FROM users WHERE department = %s", ("Engineering",))

# Use iterator pattern for memory-efficient row processing
for row in cursor:
    user_id, name = row
    print(f"Processing user: {name}")
    # Process each row individually

cursor.close() 
db.close()

Context Manager with Cursors

import MySQLdb

with MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test") as db:
    with db.cursor(MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("SELECT COUNT(*) as total FROM users")
        result = cursor.fetchone()
        print(f"Total users: {result['total']}")
        
        cursor.execute("SELECT name FROM users ORDER BY created_at DESC LIMIT 5")
        recent_users = cursor.fetchall()
        print("Recent users:")
        for user in recent_users:
            print(f"- {user['name']}")
    # Cursor automatically closed here
# Connection automatically closed here

Multiple Result Sets

import MySQLdb

db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")
cursor = db.cursor()

# Execute query that returns multiple result sets
cursor.execute("CALL multi_result_procedure()")

# Process first result set
results1 = cursor.fetchall()
print(f"First result set: {len(results1)} rows")

# Move to next result set
if cursor.nextset():
    results2 = cursor.fetchall()
    print(f"Second result set: {len(results2)} rows")

cursor.close()
db.close()

Install with Tessl CLI

npx tessl i tessl/pypi-mysql-python

docs

connections.md

constants-errors.md

cursors.md

escaping.md

index.md

low-level.md

types.md

tile.json