2003 (HY000):无法连接到“***.database.windows.net:3306”上的 MySQL 服务器 (10060)

2003 (HY000): Can't connect to MySQL server on '***.database.windows.net:3306' (10060)

我正在尝试使用 mysql-connector-python 库连接 Azure SQL 数据库。 但是我遇到了上述错误。 在这里我附上我的代码以供参考。 我已获得在防火墙中访问我的 IP 的权限。

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

您不能使用 MySQL 连接器连接到 Azure SQL 数据库。 MySQL database and an Azure SQL database.

有区别

Azure SQL 不是 MySQL

您可以使用 Azure Database for MySQL as a database, or check out this example on how to Use Python to query a SQL database,它使用 ODBC 驱动程序。正如您在链接文章中看到的那样,它们存在于 macOS,Ubuntu 和 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()