Python interface to MySQL databases implementing the Python Database API version 2.0 specification.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Database connection functionality for establishing, configuring, and managing MySQL database connections with comprehensive transaction control and connection lifecycle management.
Primary functions for creating database connections with flexible parameter handling.
def connect(host=None, user=None, passwd=None, db=None, port=3306, unix_socket=None,
charset='latin1', sql_mode=None, read_default_file=None, conv=None,
use_unicode=None, client_flag=0, cursorclass=None, init_command=None,
connect_timeout=None, read_default_group=None, read_timeout=None,
write_timeout=None, compress=None, named_pipe=None, no_delay=None,
autocommit=False, db_type=None, **kwargs):
"""
Create a database connection.
Parameters:
- host (str): MySQL server hostname
- user (str): Username for authentication
- passwd (str): Password for authentication
- db (str): Database name to connect to
- port (int): TCP port number (default 3306)
- unix_socket (str): Unix socket path for local connections
- charset (str): Character set for connection (default 'latin1')
- sql_mode (str): SQL mode string
- read_default_file (str): MySQL configuration file path
- conv (dict): Custom type conversion dictionary
- use_unicode (bool): Enable Unicode support
- client_flag (int): Client connection flags
- cursorclass (class): Default cursor class for connection
- init_command (str): Command to execute on connection
- connect_timeout (int): Connection timeout in seconds
- autocommit (bool): Enable autocommit mode
Returns:
Connection: Database connection object
"""
# Aliases for connect function
Connect = connect
Connection = connectMain database connection class providing transaction control, cursor creation, and connection management.
class Connection:
"""Database connection object providing DB API 2.0 interface."""
def __init__(self, *args, **kwargs):
"""Initialize database connection with parameters from connect()."""
def autocommit(self, on):
"""
Set autocommit mode.
Parameters:
- on (bool): True to enable autocommit, False to disable
"""
def begin(self):
"""Begin a new transaction explicitly."""
def commit(self):
"""Commit the current transaction."""
def rollback(self):
"""Rollback the current transaction."""
def cursor(self, cursorclass=None):
"""
Create a cursor object for executing queries.
Parameters:
- cursorclass (class, optional): Cursor class to use
Returns:
Cursor: New cursor object
"""
def close(self):
"""Close the database connection."""
def literal(self, o):
"""
Convert Python object to SQL literal representation.
Parameters:
- o: Python object to convert
Returns:
str: SQL literal string
"""
def set_character_set(self, charset):
"""
Set the character set for the connection.
Parameters:
- charset (str): Character set name (e.g., 'utf8', 'latin1')
"""
def set_sql_mode(self, sql_mode):
"""
Set SQL mode for the connection.
Parameters:
- sql_mode (str): SQL mode string
"""
def show_warnings(self):
"""
Show MySQL warnings from the last operation.
Returns:
tuple: Warning information
"""
def warning_count(self):
"""
Get the number of warnings from the last operation.
Returns:
int: Number of warnings
"""
def character_set_name(self):
"""
Get the default character set for the current connection.
Returns:
str: Character set name (e.g., 'latin1', 'utf8')
"""
def get_server_info(self):
"""
Get MySQL server version string.
Returns:
str: Server version information
"""
def get_host_info(self):
"""
Get connection host information string.
Returns:
str: Host connection details
"""
def get_proto_info(self):
"""
Get MySQL protocol version.
Returns:
int: Protocol version number
"""
def thread_id(self):
"""
Get connection thread ID.
This value can be used with kill() to terminate the connection thread.
Returns:
int: MySQL connection thread ID
"""
def stat(self):
"""
Get MySQL server statistics.
Returns:
str: Server status information
"""
def kill(self, pid):
"""
Kill a MySQL server thread.
Parameters:
- pid (int): Thread ID to kill
"""
def select_db(self, db):
"""
Change the default database for the connection.
Parameters:
- db (str): Database name to select
"""
def escape(self, obj, mapping):
"""
Escape object using connection's character set.
Parameters:
- obj: Object to escape
- mapping: Type conversion mapping
Returns:
str: Escaped string representation
"""
def escape_string(self, s):
"""
Escape string using connection's character set.
Preferred over module-level escape_string() as it handles
character sets properly.
Parameters:
- s (str): String to escape
Returns:
str: Escaped string
"""
def __enter__(self):
"""
Context manager entry.
Returns:
Connection: Self for context management
"""
def __exit__(self, exc, value, tb):
"""
Context manager exit with automatic cleanup.
Parameters:
- exc: Exception type
- value: Exception value
- tb: Traceback object
"""Connection objects expose various attributes from the underlying MySQL connection.
# Connection attributes (read-only properties)
connection.open: int # Connection status
connection.server_capabilities: int # Server capability flags
connection.client_flag: int # Client connection flags
connection.client_info: str # Client library information
connection.host_info: str # Host connection information
connection.server_info: str # Server version information
connection.proto_info: int # Protocol version
connection.thread_id: int # Connection thread IDHelper functions for connection management and error handling.
def defaulterrorhandler(connection, cursor, errorclass, errorvalue):
"""
Default error handler for database operations.
Parameters:
- connection: Database connection object
- cursor: Cursor object where error occurred
- errorclass: Exception class to raise
- errorvalue: Exception instance or error message
"""
def numeric_part(s):
"""
Extract numeric part from version string.
Parameters:
- s (str): Version string
Returns:
str: Numeric portion of version string
"""import MySQLdb
# Connect with basic parameters
db = MySQLdb.connect(
host="localhost",
user="myuser",
passwd="mypassword",
db="mydatabase"
)
# Use connection
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print(f"MySQL version: {version[0]}")
# Clean up
cursor.close()
db.close()import MySQLdb
# Connect with advanced configuration
db = MySQLdb.connect(
host="localhost",
user="myuser",
passwd="mypassword",
db="mydatabase",
charset="utf8",
use_unicode=True,
autocommit=False,
connect_timeout=10,
cursorclass=MySQLdb.cursors.DictCursor
)
# Connection is ready with UTF-8 support and dictionary cursorsimport MySQLdb
with MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test") as db:
try:
# Begin transaction
db.begin()
cursor = db.cursor()
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)",
("John Doe", "john@example.com"))
cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE user_id = %s", (1,))
# Commit if all operations succeed
db.commit()
print("Transaction completed successfully")
except MySQLdb.Error as e:
# Rollback on any error
db.rollback()
print(f"Transaction failed: {e}")
raiseimport MySQLdb
# Automatic connection cleanup
with MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test") as db:
with db.cursor() as cursor:
cursor.execute("SELECT * FROM users LIMIT 5")
for row in cursor.fetchall():
print(row)
# Cursor automatically closed
# Connection automatically closedInstall with Tessl CLI
npx tessl i tessl/pypi-mysql-python