mysqldb._exceptions.operationalerror:(2002,; c可以连接到服务器上的服务器上'' servername> .database.windows.net.net')| django+ azure+ mysql

发布于 2025-01-31 02:54:03 字数 1461 浏览 5 评论 0原文

我在我的本地计算机中连接我的Django应用程序与Azure的MySQL数据库有问题吗?我在规则中添加了IP,并正在与此联系:

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '<servername>.database.windows.net',
        'PORT': '3306',
        'NAME': '<database_name>',
        'USER': '<admin>@<servername>',
        'PASSWORD': '<cecret>',
        'OPTIONS': {'ssl': {'pem': 'tls.pem'} }
    },

我可以使用AzureDatastudio进行连接,但不能在Django中使用此配置。我对我的主机进行了介绍,发现了一堆开放端口,但33061433绑定到SQL服务器。

django的runserver显示mysqldb._expections.operationalerror:(2002,“无法连接到'&lt; servername&gt; .database..database.windows.windows.net.net'(115))即使我在其中运行了该配置,即使我有该服务器和数据库。

一个示例php Azure Portal中的查询字符串具有:

$conn = new PDO("sqlsrv:server = tcp:<server_name>.database.windows.net,1433; Database = <database_name>", "<admin>", "{your_password_here}");

因此,我假设我应该连接到1433,但仅3306从DataStudio工作。来自python manage.py runserver它显示django.db.utils.utils.utils.operationalerror :( 2013年,“'handshake tic'Handshake:handshake to'Handshake:读取初始通信数据包',系统错误:104”)如果我尝试端口1433。我对此有所了解。

校正-1:3306似乎与Azure DataStudio无法使用。但是,在Django设置中使用1433甚至都不会初始化连接。

I'm having issues connecting my Django app in my local machine to MySql Database in Azure? I added my IP in the Rules and am connecting with this:

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '<servername>.database.windows.net',
        'PORT': '3306',
        'NAME': '<database_name>',
        'USER': '<admin>@<servername>',
        'PASSWORD': '<cecret>',
        'OPTIONS': {'ssl': {'pem': 'tls.pem'} }
    },

I can connect using AzureDataStudio, but not with this configuration in django. I Nmaped my host, found a bunch of open ports but 3306 and 1433 are bound to Sql servers.

Django's runserver shows MySQLdb._exceptions.OperationalError: (2002, "Can't connect to server on '<servername>.database.windows.net' (115)") with this configuration even if I have that server and database within it running.

One example php query string in Azure portal has:

$conn = new PDO("sqlsrv:server = tcp:<server_name>.database.windows.net,1433; Database = <database_name>", "<admin>", "{your_password_here}");

So, I'm assuming I should connect to 1433 but only 3306 works from DataStudio. From python manage.py runserver it shows django.db.utils.OperationalError: (2013, "Lost connection to server at 'handshake: reading initial communication packet', system error: 104") if I try port 1433. I'm at the limit of my knowledge regarding this.

Correction-1: 3306 doesn't seem to work with Azure DataStudio. But using 1433 in Django settings won't even initialize connection.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

睫毛溺水了 2025-02-07 02:54:03

您需要在本地计算机中安装MySQL连接器,以使用以下命令将Python与MySQL的Azure数据库连接。

pip安装mysql-connector-python

稍后在服务器的概述页面上,记下服务器名称 服务器管理员admin登录名

将代码示例添加到文件中。在代码中,替换&lt; myDemoserver&gt;&lt; myadmin&gt;&lt; mypassword&gt;&gt; ,并且具有MySQL Server和数据库值的占位符。

注意: ssl默认是在MySQL服务器的Azure数据库上启用的。您可能需要下载 digicertglobalrootg2 ssl证书与当地环境连接。 替换ssl_ca在计算机上使用此文件的路径中的代码中的值。

import mysql.connector
from mysql.connector import errorcode

# Obtain connection string information from the portal

config = {
  'host':'<mydemoserver>.mysql.database.azure.com',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
}

# Construct connection string

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

  # Drop previous table of same name if one exists
  cursor.execute("DROP TABLE IF EXISTS inventory;")
  print("Finished dropping table (if existed).")

  # Create table
  cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
  print("Finished creating table.")

  # Insert some data into table
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
  print("Inserted",cursor.rowcount,"row(s) of data.")
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
  print("Inserted",cursor.rowcount,"row(s) of data.")
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
  print("Inserted",cursor.rowcount,"row(s) of data.")

  # Cleanup
  conn.commit()
  cursor.close()
  conn.close()
  print("Done.")

请参阅此官方教程

You need to install the MySQL connector in your local machine to connect the Python with Azure Database for MySQL using below command.

pip install mysql-connector-python

Later, on server's Overview page, make a note of the Server name and Server admin login name.

enter image description here

Add the code example to the file. In the code, replace the <mydemoserver>, <myadmin>, <mypassword>, and <mydatabase> placeholders with the values for your MySQL server and database.

Note: SSL is enabled by default on Azure Database for MySQL servers. You may need to download the DigiCertGlobalRootG2 SSL certificate to connect from your local environment. Replace the ssl_ca value in the code with path to this file on your computer.

import mysql.connector
from mysql.connector import errorcode

# Obtain connection string information from the portal

config = {
  'host':'<mydemoserver>.mysql.database.azure.com',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
}

# Construct connection string

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

  # Drop previous table of same name if one exists
  cursor.execute("DROP TABLE IF EXISTS inventory;")
  print("Finished dropping table (if existed).")

  # Create table
  cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
  print("Finished creating table.")

  # Insert some data into table
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
  print("Inserted",cursor.rowcount,"row(s) of data.")
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
  print("Inserted",cursor.rowcount,"row(s) of data.")
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
  print("Inserted",cursor.rowcount,"row(s) of data.")

  # Cleanup
  conn.commit()
  cursor.close()
  conn.close()
  print("Done.")

Refer the steps given in this official tutorial to deploy the same.

窝囊感情。 2025-02-07 02:54:03

显然,我正在使用连接字符串和不支持我正在使用的“ MySQL数据库”的后端。我仍然对它的工作方式感到模糊,但它继续存在。

我为MySQL服务器创建了一个新的Azure数据库,并在那里创建了一个新数据库。然后使用 @utkarshpal-Mt提供的连接字符串在我的原始Django的database = {}条目中使用。不必做其他事情。它刚刚连接。

注意:您确实要求通过该证书。

EDIT1:如果您正在使用,就像我一样。

然后您需要使用 this mssql-django 与适当的驱动程序。您可以在PYPI页面中找到有关使用此后端的详细信息。

Apparently I was using connection string and backend that didn't support the "MySql database" I was using. I'm still vague on how it worked but here it goes.

I created a new Azure Database for MySql servers and created a new Database there. Then used connection strings as provided by @UtkarshPal-MT in my original Django's DATABASE={} entry. Didn't have to do anything else. It just connected.

Note: You do compulsorily require to pass that certificate.

Edit1: If you're using this, as I did.
enter image description here

Then you need to use this mssql-django external backend with proper drivers. You can find details on using this backend in that PyPi page.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文