Their is a error when connecting Python with MySQL database

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()

nd this is the error I receive:

Traceback (most recent call last):
File “01_python-mysql-connect.py”, line 23, in
connect()
File “01_python-mysql-connect.py”, line 19, in connect
conn.close()
UnboundLocalError: local variable ‘conn’ referenced before assignment AWS Certified
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.

Hi Soujanya Bargavi,

Let’s clear connectivity issues first. Can you connect to the database with telnet using the above address?

I mean something like the following:
$ telnet localhost 3306

This exception is the base class for all other exceptions in the errors module. It can be used to catch all errors in a single except statement.

The following example shows how we could catch syntax errors:

import mysql.connector

try:
cnx = mysql.connector.connect(user=‘scott’, database=‘employees’)
cursor = cnx.cursor()
cursor.execute(“SELECT * FORM employees”) # Syntax error in query
cnx.close()
except mysql.connector.Error as err:
print(“Something went wrong: {}”.format(err))`
Initializing the exception supports a few optional arguments, namely msg, errno, values and sqlstate. All of them are optional and default to None. errors.Error is internally used by Connector/Python to raise MySQL client and server errors and should not be used by your application to raise exceptions.

Nikjohn