When using a connection pool in mysql-connector-python, calling the .close() method on a connection object does not actually terminate the physical TCP connection to the MySQL server; instead, it returns the connection to the pool so it can be reused by other parts of your application. This mechanism prevents the high overhead of establishing a new handshake and authentication process every time your code needs to interact with the database, significantly improving performance in high-traffic applications.

What You'll Need

  • Python 3.x installed on your system.
  • The mysql-connector-python library installed via pip.
  • A running MySQL server instance with a database and user account created.
  • Basic familiarity with Python context managers or try-finally blocks.

Step-by-Step

  1. Initialize the Connection Pool: Start by importing mysql.connector.pooling. Create a pool instance using mysql.connector.pooling.MySQLConnectionPool. You must provide a pool name and a dictionary of configuration details (host, user, password, database). Set the pool_size attribute to determine how many physical connections the pool should maintain (the default is usually 5).
  2. Request a Connection from the Pool: Instead of calling mysql.connector.connect(), call the get_connection() method on your pool object. This action checks the pool for an available, idle connection. If one exists, the pool hands it to your code. If no idle connections exist and the pool has not yet reached its pool_size limit, it creates a new physical connection. If the limit is reached, the request will wait or raise an error depending on your configuration.
  3. Execute Your Database Operations: Use the connection object to create a cursor and execute your SQL queries. At this stage, the connection is marked as "active" or "in use" within the pool's internal registry. No other thread or function can use this specific connection until it is released.
  4. Call the .close() Method: Once your transaction or query is complete, call connection.close(). Because this connection object was spawned from a MySQLConnectionPool, the connector overrides the standard close behavior. Rather than sending a COM_QUIT command to the MySQL server to kill the session, the connector clears the session state (like resetting temporary tables or rolling back uncommitted transactions) and places the connection back into the idle queue.
  5. Verify the Return: To confirm the connection returned to the pool, you can attempt to request multiple connections in a loop. If you close them properly, you will notice that you can request connections indefinitely without hitting the pool_size limit. If you fail to call .close(), you will quickly encounter a PoolError stating that no connections are available.

Common Mistakes

One of the most frequent errors is forgetting to call .close() entirely. In a non-pooled environment, this might just lead to a slow leak of connections until the server hits max_connections. In a pooled environment, this is catastrophic because you will exhaust your pool_size (e.g., 5 or 10 connections) almost instantly. Once the pool is empty and all connections are "leaked" (still marked as active but not being used), your application will hang or crash on the next get_connection() call.

Another mistake is attempting to manually manage the physical connection state. Some developers try to use connection.disconnect() or similar low-level methods to ensure the connection is truly gone. Doing this with a pooled connection can corrupt the pool's internal tracking, leading to "stale connection" errors where the pool thinks a connection is available, but the physical socket has been closed by the client or the server.

Finally, developers often confuse the cursor.close() method with connection.close(). Closing the cursor only cleans up the result set and the local cursor object; it does not release the connection back to the pool. You must explicitly close the connection object itself to make it available for other requests.

Tips

To ensure connections are always returned to the pool regardless of whether an error occurs, always use a try...finally block or a context manager. The finally block is the safest place to put connection.close() because it executes even if a database exception is raised during the query execution.

If your application is highly concurrent, tune your pool_size based on your MySQL server's max_connections setting. If you have five application servers each with a pool size of 20, you need at least 100 available slots on the MySQL server. If the server limit is lower than the aggregate pool sizes, some application instances will fail to start or crash during peak load.

For long-running applications, be aware of the MySQL wait_timeout variable. If a connection sits idle in the pool longer than this timeout, the MySQL server will close it on the server side. The next time your Python code calls get_connection(), the pool might hand you a "dead" connection. To mitigate this, implement a simple validation check or wrap your database calls in a retry logic that catches communication errors and requests a fresh connection.

Troubleshooting

If you encounter a mysql.connector.errors.PoolError: Failed getting connection; pool exhausted, the first step is to audit your code for any path where connection.close() is skipped. Check your except blocks; if you return from a function inside an except block before reaching the close() call, that connection is lost to the pool until the process restarts.

If you see OperationalError: MySQL Connection not available, it usually means the server timed out the connection while it was idling in the pool. To fix this, check your MySQL server's wait_timeout and interactive_timeout settings. You can increase these values in the MySQL configuration file (my.cnf or my.ini) or implement a "heartbeat" query (like SELECT 1) to keep connections alive.

If the application becomes sluggish despite using a pool, check the pool_size. If the size is too small, threads will spend significant time waiting for a connection to be returned to the pool. Monitor the number of active vs. idle connections using the MySQL command SHOW PROCESSLIST; to see if connections are lingering longer than necessary.

Frequently Asked Questions

Does close() actually disconnect from the server?

No. When using a connection pool, close() simply marks the connection as available and returns it to the pool's internal list. The physical TCP socket remains open to avoid the cost of reconnecting.

What happens if I don't call close() on a pooled connection?

The connection remains marked as "in use." Once you have requested as many connections as your pool_size allows, the pool will be exhausted, and subsequent calls to get_connection() will fail.

Can I change the pool size after the pool is created?

No, the pool_size is defined during the instantiation of the MySQLConnectionPool object and cannot be changed dynamically. You must restart the application with a new configuration to change the size.

Is it safe to share one connection across multiple threads?

No. MySQL connections are not thread-safe. This is exactly why pooling is used: each thread should call get_connection(), perform its work, and then call close() to return it, ensuring that no two threads use the same physical connection simultaneously.

How do I truly kill a pooled connection?

If you need to completely remove a connection from the pool (for example, if you suspect the connection is corrupted), you generally have to let the pool handle it via timeouts or restart the application. The mysql-connector-python pool is designed to manage the lifecycle automatically.