0

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.

Anish
  • 19
  • 1
  • 8
  • Port 1433 is for Azure SQL Database and SQL Server; which is a completely different product to MySQL. I have corrected also your tags. – Thom A May 22 '22 at 09:17
  • So what do I use in my Django settings file? It clearly works with 1433 with DataStudio. So maybe there's something I misconfigured in the portal? I'm lost. – Anish May 22 '22 at 17:15
  • Do you mean Azure Data Studio? That connects to SQL Server not MySQL. Perhaps the problem is you don't know what RDBMS you are using... – Thom A May 22 '22 at 17:22
  • I don't. This was my small personal project which took nice turns and made me implement stuffs I haven't studied. :) And yes I realize Azure Data Studio connects to the server, since I can see all its databases. So how do I connect my local app to that cloud database? Maybe you can direct me to stuffs I can read? I've read all docs regarding Django+Azure MySql and tried every combinations on the settings.pyvariables. – Anish May 23 '22 at 14:36
  • Sounds like you think that SQL Server and MySQL are the same; they are completely different products. If you are using ADS to connect to a SQL Server instance, using the engine `django.db.backends.mysql` is never going to work; that's designed for MySQL. – Thom A May 23 '22 at 14:39
  • Oh wow, that's it. Thank you for pointing that out. I created another "Azure Database for MySql Server" as seen from @UtkarshPal-MT 's screenshot and it worked. I'm vague on this topic and don't know what's going on even though I managed to figure out my fault and rectify it. So have to wait for database class to start to dig deeper. Thank you. – Anish May 23 '22 at 16:56

2 Answers2

0

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.

Utkarsh Pal
  • 4,079
  • 1
  • 5
  • 14
  • Thanks for this purely pythonic solution but I was hoping for correct parameters to pass in Django's settings.py file and let it handle the connection itself rather than implementing my own. This was supposed to be my last option. – Anish May 23 '22 at 15:16
0

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.

Anish
  • 19
  • 1
  • 8