skip to Main Content

I am using a simple python function to connect to a MySQL database.I receive an error saying a variable is referenced before it is assigned, but this would not be the case if the connection had successfully established. Why is the connection failing?

I am using Ubuntu Linux 18.04. I am running xampp 7.3 to host the mySQL and apache servers and am using phpmyadmin to access the database.I am running my code with python 3.

This is my code:

import mysql.connector
from mysql.connector import Error

def connect():
    """ Connect to MySQL database """

    try:
        conn = mysql.connector.connect(host='localhost',
                               database='myDB',
                               user='xxx',
                               password='yyy!')

        if conn.is_connected():
            print('Connected to MySQL database')

    except Error as e:
        print(e)

    finally:
        conn.close()

if __name__ == '__main__':
connect()

And this is the error I receive:

Traceback (most recent call last):
  File "01_python-mysql-connect.py", line 23, in <module>
     connect()
  File "01_python-mysql-connect.py", line 19, in connect
     conn.close()
UnboundLocalError: local variable 'conn' referenced before assignment

I am expecting a successful connection to the database. I believe something could be wrong with my configurations but don’t know where to start in solving the problem. Thank you.

2

Answers


  1. This line

    conn = mysql.connector.connect(host='localhost',
                               database='myDB',
                               user='xxx',
                               password='yyy!')
    

    is failing. So conn never gets a value assigned to it. But you have a try...except...finally block and in the finally clause your code is doing conn.close(). But conn hasn’t been assigned because the statement that was supposed to assign it a value failed. That is why you are seeing the message local variable ‘conn’ referenced before assignment. To discover what is wrong, move the call to close out of the finally clause and put it before the except. You can always move it back later.

    Login or Signup to reply.
  2. If the mysql.connector.connect() call fails, conn will not be assigned, hence the “referenced before assignment” exception.

    This is an ideal use case for the contextlib.closing context manager, I think. Try something like this:

    from contextlib import closing
    
    try:
        with closing(mysql.connector.connect(...)) as conn:
            if conn.is_connected():
                print('Connected to MySQL database')
    
    except Error as e:
        print(e)
    

    This will cleanly and reliably take care of closing your connection for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search