- Tagged:
- Azure Data Services
- MySQL
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 theSet up your Python beginner development environment with Visual Studio Code Microsoft Learn Module.
Install MySQL connector
Open the command prompt and run the following command to install the MySQL connector for Python.
1
pip install mysql-connector-python
Open Visual Studio Code and create a new Python file. Add the following command and selectRun.
1
importmysql.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).
Sign in toAzure Portal, expand the left navigation panel and selectAll resources.
Then, select the Database that you created in thepart 1.
In theOverview tab, you can see theServer name andServer admin login name.
Create Connection
Open Visual Studio Code and create a new Python file nameddb1.py. Add the following code to connect to your database:
|
|
where:
username
is the admin login name,server
refers to the server name,password
is the password of the admin anddemodb
is the name of the database that you created inpart 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.