{"id":7825,"library":"types-mysqlclient","title":"Typing stubs for mysqlclient","description":"types-mysqlclient provides static type annotations (stubs) for the popular `mysqlclient` Python package, which is a MySQL database connector. It enables type checkers like MyPy and Pyright to analyze code using `mysqlclient` for type correctness. This package is part of the typeshed project and is released automatically, typically daily, to PyPI, aiming to provide accurate annotations for `mysqlclient==2.2.*`.","status":"active","version":"2.2.0.20260408","language":"en","source_language":"en","source_url":"https://github.com/python/typeshed","tags":["typing","stubs","mysql","database","typeshed"],"install":[{"cmd":"pip install types-mysqlclient","lang":"bash","label":"Install the type stubs"},{"cmd":"pip install mysqlclient","lang":"bash","label":"Install the runtime package (required)"},{"cmd":"sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config","lang":"bash","label":"System dependencies (Ubuntu/Debian)"},{"cmd":"sudo yum install python3-devel mysql-devel pkgconfig","lang":"bash","label":"System dependencies (Red Hat/CentOS)"}],"dependencies":[{"reason":"Runtime dependency for which these stubs provide types.","package":"mysqlclient","optional":false},{"reason":"Required system headers for building mysqlclient.","package":"python3-dev","optional":false},{"reason":"Required MySQL client development libraries for building mysqlclient (Debian/Ubuntu).","package":"default-libmysqlclient-dev","optional":false},{"reason":"Required MySQL client development libraries for building mysqlclient (Red Hat/CentOS).","package":"mysql-devel","optional":false},{"reason":"General build tools for compiling C extensions (Debian/Ubuntu).","package":"build-essential","optional":false},{"reason":"Tool to locate and configure build dependencies.","package":"pkg-config","optional":false}],"imports":[{"note":"`mysqlclient` is the package name; `MySQLdb` is the module it exposes, adhering to the DB-API 2.0 standard.","wrong":"import mysqlclient","symbol":"MySQLdb","correct":"import MySQLdb"}],"quickstart":{"code":"import MySQLdb\nimport os\n\nhost = os.environ.get('MYSQL_HOST', '127.0.0.1')\nuser = os.environ.get('MYSQL_USER', 'root')\npassword = os.environ.get('MYSQL_PASSWORD', 'password')\ndatabase = os.environ.get('MYSQL_DATABASE', 'testdb')\n\nconn = None\ntry:\n    # Establish a connection to the database\n    conn = MySQLdb.connect(host=host, user=user, password=password, database=database)\n    print(\"Successfully connected to MySQL database!\")\n\n    # Create a cursor object\n    cursor = conn.cursor()\n\n    # Execute a query\n    cursor.execute(\"SELECT VERSION();\")\n\n    # Fetch and print the result\n    result = cursor.fetchone()\n    print(f\"MySQL Database version: {result[0]}\")\n\n    # Example: Create a table (if not exists)\n    cursor.execute(\"CREATE TABLE IF NOT EXISTS example_table (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255));\")\n    print(\"Table 'example_table' ensured to exist.\")\n    conn.commit()\n\n    # Example: Insert data\n    cursor.execute(\"INSERT INTO example_table (name) VALUES (%s);\", (\"Test Name\",))\n    print(\"Data inserted.\")\n    conn.commit()\n\n    # Example: Select data\n    cursor.execute(\"SELECT id, name FROM example_table;\")\n    rows = cursor.fetchall()\n    print(\"Data in example_table:\")\n    for row in rows:\n        print(f\"  ID: {row[0]}, Name: {row[1]}\")\n\nexcept MySQLdb.Error as e:\n    print(f\"Error connecting to or interacting with MySQL: {e}\")\n    if conn:\n        conn.rollback()\nfinally:\n    if conn:\n        conn.close()\n        print(\"Database connection closed.\")","lang":"python","description":"This quickstart demonstrates how to connect to a MySQL database using the `MySQLdb` module (provided by `mysqlclient`), execute a simple query, create a table, insert data, and fetch results. It includes basic error handling and uses environment variables for sensitive connection details, which is a common practice in production environments. Ensure `mysqlclient` and its system dependencies are installed before running."},"warnings":[{"fix":"Pin your `types-mysqlclient` dependency to a specific version or a specific date-based component of the version in your `requirements.txt` (e.g., `types-mysqlclient==2.2.0.20260408`) and update deliberately after testing.","message":"Stub versions can introduce type-checking breaking changes. While `typeshed` aims for stability, any update to `types-mysqlclient` (even a patch version) might reveal type inconsistencies in your code due to improved or corrected annotations.","severity":"breaking","affected_versions":"All versions of types-mysqlclient (especially across dates in the version string, e.g., 2.2.0.20260402 -> 2.2.0.20260408)"},{"fix":"Before `pip install mysqlclient`, ensure you install required system packages like `python3-dev`, `default-libmysqlclient-dev` (Ubuntu/Debian), or `python3-devel`, `mysql-devel` (Red Hat/CentOS), along with `build-essential` and `pkg-config`.","message":"The `mysqlclient` package (the runtime library) often fails to install with a 'Failed building wheel' error if necessary system-level development headers and libraries are missing. This is not an issue with `types-mysqlclient` itself, but with its runtime dependency.","severity":"gotcha","affected_versions":"All versions of mysqlclient and types-mysqlclient"},{"fix":"Change literal `%` to `%%` in your SQL query strings where you don't intend it to be a parameter placeholder. Example: `cursor.execute(\"SELECT '50%% complete' AS progress;\")`","message":"When using `cursor.execute()` with SQL statements that contain literal percent signs (`%`), they must be escaped as `%%` if they are not intended as parameter placeholders. Failure to do so can lead to `TypeError: not all arguments converted during string formatting` or incorrect query execution.","severity":"gotcha","affected_versions":"All versions of mysqlclient"},{"fix":"Always import and use `MySQLdb` instead of `_mysql` for database interactions to ensure adherence to the Python DB API Specification (PEP 249) and better portability.","message":"The direct use of the low-level `_mysql` module, which is part of the `mysqlclient` package, is discouraged. It is less portable and works at a lower level of abstraction than `MySQLdb`.","severity":"deprecated","affected_versions":"All versions of mysqlclient"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Install system dependencies: `sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config` (Ubuntu/Debian) or `sudo yum install python3-devel mysql-devel pkgconfig` (Red Hat/CentOS).","cause":"Missing system-level development headers for Python and MySQL, or build tools.","error":"Failed building wheel for mysqlclient"},{"fix":"Change `import mysqlclient` to `import MySQLdb`.","cause":"Attempting to import the package name `mysqlclient` directly instead of the `MySQLdb` module it provides.","error":"ImportError: No module named 'mysqlclient'"},{"fix":"Install `pkg-config`: `sudo apt-get install pkg-config` (Ubuntu/Debian) or `sudo yum install pkgconfig` (Red Hat/CentOS).","cause":"The `pkg-config` utility, required by `mysqlclient`'s build process to locate libraries, is not installed or not in the system's PATH.","error":"pkg-config: not found"},{"fix":"Double-check your connection parameters (host, user, password, database) in `MySQLdb.connect()` against your MySQL server configuration. Ensure the user has privileges from the connecting host.","cause":"Incorrect username, password, or host for the MySQL database connection.","error":"(_mysql_exceptions.OperationalError) (1045, \"Access denied for user 'youruser'@'localhost' (using password: YES)\")"},{"fix":"Check `wait_timeout` and `max_allowed_packet` server variables. Increase them if necessary. Ensure network stability. Implement connection pooling or re-connection logic in your application.","cause":"The connection to the MySQL server was lost, often due to inactivity timeout (`wait_timeout`), a large packet size exceeding `max_allowed_packet`, or the server restarting.","error":"(_mysql_exceptions.OperationalError) (2006, 'MySQL server has gone away')"}]}