I will re-iterate the best practice at everyone who comes across the sql connection using MySQLdb or any other package to connect python2/3 needs to know this

(Following mock run assumes that you have a table named tablename in your sql database. It has got 4 columns/fields with names field1,field2,field3,field4). If your connection is local (same machine) then it is 127.0.0.1 also known as "localhost".

The process is to be simple 7 steps

  1. Create connection
  2. Create cursor
  3. Create Query string
  4. Execute the query
  5. Commit to the query
  6. Close the cursor
  7. Close the connection

Here is a simple step by stem mock run

mydb = MySQLdb.connect(host=host, user=user, passwd=passwd, db=database, charset="utf8")
cursor = mydb.cursor()
query = "INSERT INTO tablename (text_for_field1, text_for_field2, text_for_field3, text_for_field4) VALUES (%s, %s, %s, %s)"
cursor.execute(query, (field1, field2, field3, field4))
mydb.commit()
cursor.close()
mydb.close()

Connection and cursor are different. connection is at the SQL level while cursor can be considered as a data element. You can have multiple cursors on the same data within single connection. It is an unusual occurrence to have multiple connections to same data from the same computer.

More has been described here "The cursor paradigm is not specific to Python but are a frequent data structure in databases themselves.

Depending on the underlying implementation it may be possible to generate several cursors sharing the same connection to a database. Closing the cursor should free resources associated to the query, including any results never fetched from the DB (or fetched but not used) but would not eliminate the connection to the database itself so you would be able to get a new cursor on the same database without the need to authenticate again."

Answer from Mandar on Stack Overflow
🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-api-mysqlconnection-close.html
MySQL :: MySQL Connector/Python Developer Guide :: 10.2.2 MySQLConnection.close() Method
For a connection obtained from a connection pool, close() does not actually close it but returns it to the pool and makes it available for subsequent connection requests. See Section 9.5, “Connector/Python Connection Pooling”.
🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-api-mysqlcursor-close.html
MySQL :: MySQL Connector/Python Developer Guide :: 10.5.6 MySQLCursor.close() Method
MySQL Connector/Python Developer Guide / ... / Connector/Python API Reference / cursor.MySQLCursor Class / MySQLCursor.close() Method ... Use close() when you are done using a cursor. This method closes the cursor, resets all results, and ensures that the cursor object has no reference to its ...
Discussions

need to close mysql connection? : Forums : PythonAnywhere
You shouldn't need a session.close, no. I'm confused about the code you quote above -- if there's no variable called Stock defined when the code is executed, it shouldn't work in either raw mysqldb or in SQLAlchemy. Are you sure you didn't accidentally delete the line where you assigned a value to Stock? giles | 12916 posts | PythonAnywhere ... More on pythonanywhere.com
🌐 pythonanywhere.com
January 4, 2017
MySQL Connector/Python not closing connection explicitly - Stack Overflow
Is using __enter__ and __exit__ ... mysql.connector in a Class and ensuring proper cleanup when used with with? 2017-01-09T03:30:41.153Z+00:00 ... @Vishal I don't think there's a single, best solution to this. It depends on how your class is to be used. The rule of thumb is to create as few connections as you can but to always close them when ... More on stackoverflow.com
🌐 stackoverflow.com
September 1, 2017
The Correct way to end a SQL connection with python?
Depending on what db module you're using. You could use a context manager like: import sqlite3 with sqlite3.connect("db.sqlite3") as db_connection5: cursor = db_connection5.cursor() sql = "SELECT Price,Stock FROM Catalog WHERE ID=%s LIMIT 1" val = (SKUC,) cursor.execute(sql, val) AddRecordCheck = cursor.fetchone() db_connection5.commit() Which will automatically close after. edit. Code block is totally not working for me today :/ (Used markdown and it worked) More on reddit.com
🌐 r/learnpython
4
3
September 12, 2021
Python Mysql-Connector. Which is better connection.close() or connection.disconnect() or connection.shutdown() - Stack Overflow
I have a question and I hope that someone could help me. To give you some context, imagine a loop like this: while True: conn = mysql.connector.connect(**args) #args without specifying poolname ... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 4
121

I will re-iterate the best practice at everyone who comes across the sql connection using MySQLdb or any other package to connect python2/3 needs to know this

(Following mock run assumes that you have a table named tablename in your sql database. It has got 4 columns/fields with names field1,field2,field3,field4). If your connection is local (same machine) then it is 127.0.0.1 also known as "localhost".

The process is to be simple 7 steps

  1. Create connection
  2. Create cursor
  3. Create Query string
  4. Execute the query
  5. Commit to the query
  6. Close the cursor
  7. Close the connection

Here is a simple step by stem mock run

mydb = MySQLdb.connect(host=host, user=user, passwd=passwd, db=database, charset="utf8")
cursor = mydb.cursor()
query = "INSERT INTO tablename (text_for_field1, text_for_field2, text_for_field3, text_for_field4) VALUES (%s, %s, %s, %s)"
cursor.execute(query, (field1, field2, field3, field4))
mydb.commit()
cursor.close()
mydb.close()

Connection and cursor are different. connection is at the SQL level while cursor can be considered as a data element. You can have multiple cursors on the same data within single connection. It is an unusual occurrence to have multiple connections to same data from the same computer.

More has been described here "The cursor paradigm is not specific to Python but are a frequent data structure in databases themselves.

Depending on the underlying implementation it may be possible to generate several cursors sharing the same connection to a database. Closing the cursor should free resources associated to the query, including any results never fetched from the DB (or fetched but not used) but would not eliminate the connection to the database itself so you would be able to get a new cursor on the same database without the need to authenticate again."

2 of 4
19

Closing the cursor as soon as you are done with it is probably the best bet, since you have no use for it anymore. However, I haven't seen anything where it's harmful to close it after the db connection. But since you can set it as:

cursor = conn.cursor()

I recommend closing it before, in case you accidentally assign it again and the DB connection is closed as this would throw an error. So you may want to close it first in order to prevent an accidental reassignment with a closed connection.

(Some don't even close it at all though as it gets collected by the garbage collector (see:In Python with sqlite is it necessary to close a cursor?))

References: When to close cursors using MySQLdb

In Python with sqlite is it necessary to close a cursor?

🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-api-mysqlconnection-shutdown.html
MySQL :: MySQL Connector/Python Developer Guide :: 10.2.33 MySQLConnection.shutdown() Method
MySQL Connector/Python Developer Guide / ... / Connector/Python API Reference / connection.MySQLConnection Class / MySQLConnection.shutdown() Method · This method closes the socket.
🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-api-mysqlconnection-disconnect.html
MySQL :: MySQL Connector/Python Developer Guide :: 10.2.20 MySQLConnection.disconnect() Method
MySQL Connector/Python Developer Guide / ... / Connector/Python API Reference / connection.MySQLConnection Class / MySQLConnection.disconnect() Method · This method tries to send a QUIT command and close the socket.
🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-api-pooledmysqlconnection-close.html
MySQL :: MySQL Connector/Python Developer Guide :: 10.4.2 PooledMySQLConnection.close() Method
MySQL Connector/Python Developer Guide / ... / Connector/Python API Reference / pooling.PooledMySQLConnection Class / PooledMySQLConnection.close() Method ... Returns a pooled connection to its connection pool.
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 9056
need to close mysql connection? : Forums : PythonAnywhere
January 4, 2017 - I need to do some complicated select from MySQL, I need to replace all with sqlalchemy or sqlalchemy on top of MySQLdb? deleted-user-1572469 | 157 posts | Jan. 5, 2017, 6:25 a.m. | permalink · Sqlalchemy can do connection pooling/automatic recycling/closing of your connections. The more web workers you have in your PythonAnywhere plan the more db connections you will be allowed. But in general you will have to setup connection pooling/recycling/disconnecting (because otherwise no matter what your limit is you will go over.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › disconnecting-database-in-python
Disconnecting Database in Python
MySQL · Javascript · PHP · Selected ... Glossary · Who is Who · PythonServer Side ProgrammingProgramming · To disconnect Database connection, use close() method....
🌐
Quora
quora.com › How-do-you-close-an-SQL-connection-in-Python
How to close an SQL connection in Python - Quora
Answer (1 of 11): It depends on which database library you’re using. Many low-level database libraries in Python follow the DB-API 2.0 standard. In that case, it’s just a matter of calling close() on the connection object: [code]conn = sqlite3.connect('spam.db') conn.execute('INSERT INTO ...
🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-api-cext-close.html
MySQL :: MySQL Connector/Python Developer Guide :: 11.8 _mysql_connector.MySQL.close() Method
MySQL Connector/Python Developer Guide / Connector/Python C Extension API Reference / _mysql_connector.MySQL.close() Method ... Closes the MySQL connection.
Top answer
1 of 2
3

It's not a config issue. When you are done with a connection you should close it by explicitly calling close. It is generally a best practice to maintain the connection for a long time as creating one takes time. It's not possible to tell from your code snippet where would be the best place to close it - it's whenever you're "done" with it; perhaps at the end of your __main__ method. Similarly, you should close the cursor explicitly when your done with it. Typically that happens after each query.

So, maybe something like:

class FooData(object):
    def __init__(self):
        ...
        try:
            self.my_cnf = os.environ['HOME'] + '/.my.cnf'
            self.my_cxn = mysql.connector.connect(option_files=self.my_cnf)

     def execute_some_query(self, query_info):
        """Runs a single query. Thus it creates a cursor to run the
           query and closes it when it's done."""

        # Note that cursor is not a member variable as it's only for the
        # life of this one query    
        cursor = self.my_cxn.cursor(dictionary=True)
        cursor.execute(...)

        # All done, close the cursor
        cursor.close()

    def close():
        """Users of this class should **always** call close when they are
           done with this class so it can clean up the DB connection."""
        self.my_cxn.close()

You might also look into the Python with statement for a nice way to ensure everything is always cleaned up.

2 of 2
0

I rewrote my class above to look like this...

class FooData(object):
    def __init__(self):
        self.myconfig = {
            'option_files': os.environ['HOME'] + '/.my.cnf',
            'database': 'nsdata'
        }
        self.mysqlcxn = None

    def __enter__(self):
        try:
            self.mysqlcxn = mysql.connector.connect(**self.myconfig)
        except mysql.connector.Error as err:
            if err.errno == 2003:
                self.mysqlcxn = None
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if self.mysqlcxn is not None and self.mysqlcxn.is_connected():
            self.mysqlcxn.close()

    def etl(self)
        ...

I can then use with ... as and ensure that I am cleaning up properly.

with FooData() as obj:
    obj.etl()

The Aborted connection messages are thus properly eliminated.

Oliver Dain's response set me on the right path and Explaining Python's '__enter__' and '__exit__' was very helpful in understanding the right way to implement my Class.

🌐
Oracle
docs.oracle.com › cd › E17952_01 › connector-python-en › connector-python-api-mysqlconnection-close.html
10.2.2 MySQLConnection.close() Method
October 25, 2025 - close() is a synonym for disconnect(). See Section 10.2.20, “MySQLConnection.disconnect() Method”. For a connection obtained from a connection pool, close() does not actually close it but returns it to the pool and makes it available for subsequent connection requests.
🌐
Reddit
reddit.com › r/learnpython › the correct way to end a sql connection with python?
r/learnpython on Reddit: The Correct way to end a SQL connection with python?
September 12, 2021 -

So ive been doing a bit more reading and i use to do a MySQL query like so :-

    cursor = db_connection5.cursor()
    sql = "SELECT Price,Stock FROM Catalog WHERE ID=%s LIMIT 1"
    val = (SKUC,) 
    cursor.execute(sql, val)
    AddRecordCheck = cursor.fetchone()
    db_connection5.commit() 

But now it has come to my attention i should be ending the connection like so:-

    cursor = db_connection5.cursor()
    sql = "SELECT Price,Stock FROM Catalog WHERE ID=%s LIMIT 1"
    val = (SKUC,) 
    cursor.execute(sql, val)
    AddRecordCheck = cursor.fetchone()
    db_connection5.commit()
    cursor.close() 

The only reason i ask is i have around 15 of the same scripts connected to my database working 24/7 and sometimes one of my other scripts connecting to the database hangs for an hour or two trying to connect at "cursor = db_connection5.cursor()" so i am starting to wonder if i have been missing something all along.

Top answer
1 of 3
3
Depending on what db module you're using. You could use a context manager like: import sqlite3 with sqlite3.connect("db.sqlite3") as db_connection5: cursor = db_connection5.cursor() sql = "SELECT Price,Stock FROM Catalog WHERE ID=%s LIMIT 1" val = (SKUC,) cursor.execute(sql, val) AddRecordCheck = cursor.fetchone() db_connection5.commit() Which will automatically close after. edit. Code block is totally not working for me today :/ (Used markdown and it worked)
2 of 3
2
Neither of your code blocks really do much with connections, but cursors. Cursors are basically just an easier way of reading query results. They'll let you pull results one at a time instead of 5 million results all at once. Depending on the library or DB, you'll also have a separate transaction concept, sometimes implicitly created and destroyed with the cursor. And cursors are typically closed automatically when they're garbage collected, like if you create it in a function then end the function without calling .close. In case, as another user mentioned, you'd usually be better off using context managers for most things, as they handle all the cleanup and closing for you: with conn.cursor() as cur: cur.execute('query') row = cur.fetchone() This is often also supported for transactions and connection: with your_sql_lib.connect(database='dbname') as conn: with conn.transaction(): with conn.cursor() as cur: cur.execute('some query that might raise an error and' 'transaction context manager will revert any changes made if it does') Just to note, I'm not really familiar with MySQL but these are pretty broad SQL/Python concepts and the library you're using looks mostly DB-API 2.0 compliant. You'll need to see the docs for the specific library you're using for the syntax and features it supports.
🌐
PYnative
pynative.com › home › python › databases › python mysql database connection using mysql connector
Python MySQL Database Connection - MySQL Connector Python
March 9, 2021 - import mysql.connector from mysql.connector import Error try: connection = mysql.connector.connect(host='localhost', database='Electronics', user='pynative', password='pynative@#29') if connection.is_connected(): db_Info = connection.get_server_info() print("Connected to MySQL Server version ", db_Info) cursor = connection.cursor() cursor.execute("select database();") record = cursor.fetchone() print("You're connected to database: ", record) except Error as e: print("Error while connecting to MySQL", e) finally: if connection.is_connected(): cursor.close() connection.close() print("MySQL conne
🌐
TutorialsPoint
tutorialspoint.com › python_data_access › python_mysql_database_connection.htm
Python MySQL - Database Connection
data = cursor.fetchone() print("Connection established to: ",data) #Closing the connection conn.close() On executing, this script produces the following output − · (myenv) D:\Projects\python\myenv>py main.py Connection established to: ('mydb',) You can also establish connection to MySQL by passing credentials (user name, password, hostname, and database name) to connection.MySQLConnection() as shown below − · from mysql.connector import (connection) #establishing the connection conn = connection.MySQLConnection(user='root', password='password', host='127.0.0.1', database='mydb') #Closing the connection conn.close()
🌐
Oracle
docs.oracle.com › cd › E17952_01 › connector-python-en › connector-python-example-connecting.html
5.1 Connecting to MySQL Using Connector/Python
May 5, 2026 - The use_pure option and C extension were added in Connector/Python 2.1.1. The following example shows how to set use_pure to False. import mysql.connector cnx = mysql.connector.connect(user='scott', password='password', host='127.0.0.1', database='employees', use_pure=False) cnx.close()
🌐
Stack Overflow
stackoverflow.com › questions › 66117620 › python-mysql-connector-which-is-better-connection-close-or-connection-disconn
Python Mysql-Connector. Which is better connection.close() or connection.disconnect() or connection.shutdown() - Stack Overflow
Unlike disconnect(), shutdown() closes the client connection without attempting to send a QUIT command to the server first. Thus, it will not block if the connection is disrupted for some reason such as network failure. But I do not figure out why you get Lost connection to MySQL server during query You may check this discussion Lost connection to MySQL server during query
🌐
Oracle
docs.oracle.com › cd › E17952_01 › connector-python-en › connector-python-api-mysqlcursor-close.html
10.5.6 MySQLCursor.close() Method
September 15, 2025 - MySQL Connector/Python Developer Guide · Use close() when you are done using a cursor. This method closes the cursor, resets all results, and ensures that the cursor object has no reference to its original connection object
🌐
MySQL
dev.mysql.com › doc › connector-python › en › connector-python-api-mysqlconnection-cmd-process-kill.html
MySQL :: MySQL Connector/Python Developer Guide :: 10.2.12 MySQLConnection.cmd_process_kill() Method
March 4, 2015 - MySQL Connector/Python Developer Guide / ... / Connector/Python API Reference / connection.MySQLConnection Class / MySQLConnection.cmd_process_kill() Method