'NameError: name 'connection' is not defined

I am trying to run a Python script in Azure automation count.
The target is to connect to a public API, check currency and write back to a MySQL database. The MySQL database is in Azure.

Here is my code:

#!/usr/bin/env python3

import requests
import mysql.connector
import os

#from dotenv import load_dotenv
from mysql.connector import Error

#load_dotenv()

needToGet = ["AED", "AUD", "CAD", "CHF", "EUR", "GBP", "HKD", "ILS", "INR", "JPY", "KWD", "MXN", "NZD", "RUB", "SEK", "TRY", "ZAR", "DKK", "NOK", "GBX"]
currency = ','.join(needToGet)

url = 'https://openexchangerates.org/api/latest.json'
path = '?app_id=2dbfde0172a54732a87ff34cbb21c8ba&symbols=' + currency
data = requests.get(url + path).json()

forInsert = []
for cur in needToGet:
    if cur in data['rates']:
        forInsert.append(data['rates'][cur])
    else:
        forInsert.append('null')

stringForInsert = ','.join(map(str, forInsert))

try:
    connection = mysql.connector.connect("*******.mysql.database.azure.com",
                                         "exchange",
                                         "exchange@*****",
                                         "******")

    mySql_insert_query = """INSERT INTO currency (""" + currency + """)
                           VALUES
                           (""" + stringForInsert + """) """

    cursor = connection.cursor()
    cursor.execute(mySql_insert_query)
    connection.commit()
    print(cursor.rowcount, "Record inserted successfully into exchange table")
    cursor.close()

except mysql.connector.Error as error:
    print("Failed to insert record into exchange table {}".format(error))

finally:
    if connection.is_connected():
        connection.close()
        print("MySQL connection is closed")

But I received the following error:

Traceback (most recent call last):  
File "C:\Temp\w4ezxc4a.mkf\3525cb9a-e211-4b86-91b4-2a7d740ce109", line 29, in <module>
        connection = mysql.connector.connect("****.mysql.database.azure.com",
File "C:\WPy64-3800\python-3.8.0.amd64\lib\site-packages\mysql\connector\__init__.py", line 273, in connect
        return MySQLConnection(*args, **kwargs)  
File "C:\WPy64-3800\python-3.8.0.amd64\lib\site-packages\mysql\connector\connection.py", line 73, in __init__
        super(MySQLConnection, self).__init__(*args, **kwargs)
TypeError: __init__() takes 1 positional argument but 5 were given
During handling of the above exception, another exception occurred:
Traceback (most recent call last):  File "C:\Temp\w4ezxc4a.mkf\3525cb9a-e211-4b86-91b4-2a7d740ce109", line 48, in <module>
        if connection.is_connected():NameError: name 'connection' is not defined

If I run the script locally, it works without issues.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source