Connect to Azure Database for MySQL using Python

This tutorial will show you how to use Python to connect to an Azure Database for MySQL. To complete the exercise, you will need to install the following tools:

  • Python 3 (make sure to add Python to your PATH)
  • Visual Studio Code or other code editor

If you need help with installing these tools, follow the instructions in the Set up your Python beginner development environment with Visual Studio Code Microsoft Learn Module.

Install MySQL connector

  1. Open the command prompt and run the following command to install the MySQL connector for Python.

    1
    
    pip install mysql-connector-python
    
  2. Open Visual Studio Code and create a new Python file. Add the following command and select Run.

    1
    
    import mysql.connector
    

    If MySQL Connector is installed successfully, the above code will be executed with no errors.

Get connection information

The next step is to collect the information that you need to connect to the Azure Database for MySQL. You need the server name, the database name, and the login credentials (username and password).

  1. Sign in to Azure Portal, expand the left navigation panel and select All resources.

    Select All resources in Azure
  2. Then, select the Database that you created in the part 1.

  3. In the Overview tab, you can see the Server name and Server admin login name.

    Database for MySQL information

Create Connection

Open Visual Studio Code and create a new Python file named db1.py. Add the following code to connect to your database:

1
2
3
4
5
6
7
8
9
import mysql.connector
# Establish the connection
conn = mysql.connector.connect(
  user='username@server', 
  password='password', 
  host= 'server.mysql.database.azure.com', 
  database="demodb"
)
print(conn)

where:

  • username is the admin login name,
  • server refers to the server name,
  • password is the password of the admin and
  • demodb is the name of the database that you created in part 1.

Next steps

Now you are ready to start working with MySQL in Python. In the following tutorials, you will use Pyhton and SQL statements to create tables, manipulate and query data in the database.

You May Also Like