I am trying to connect Azure SQL database using mysql-connector-python library. But I am getting above mentioned error. Here I am attaching my code for reference. I have been given access to my IP in the firewall.
import mysql.connector
from mysql.connector import errorcode
# Obtain connection string information from the portal
# Construct connection string
config = {
'host':'db.database.windows.net',
'user':'server@db',
'password':'********',
'database':'db',
'client_flags': [mysql.connector.ClientFlag.SSL],
'ssl_ca': 'DigiCertGlobalRootG2.crt.pem'
}
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = conn.cursor()
You cannot use the MySQL connector to connect to an Azure SQL database. There's a difference between a MySQL database and an Azure SQL database.
You can either use Azure Database for MySQL as a database, or check out this example on how to Use Python to query a SQL database, which uses an ODBC driver. As you can see in the linked article, they exist for macOS, Ubuntu and Windows.
import pyodbc
server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '{<password>}'
driver= '{ODBC Driver 17 for SQL Server}'
with pyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT TOP 3 name, collation_name FROM sys.databases")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()