Connecting to Azure SQL Database from Python

Connecting to Azure SQL Database from Python

Azure SQL Database is a cloud-based database service offered by Microsoft. In this document, we will discuss how to connect to an Azure SQL Database using Python.

Prerequisites

Before starting, make sure you have the following:

  • An Azure account

  • An Azure SQL Database instance

  • Python installed on your machine

  • The pyodbc library installed in Python

Steps

Follow the steps below to connect to your Azure SQL Database:

  1. Open your Azure portal and navigate to your SQL Database instance.

  2. Click on “Show database connection strings” from the Overview page.

  3. Copy the connection string for Python.

  4. Open your Python editor or IDE and install the pyodbc library using the following command:

pip install pyodbcp

5. Import the pyodbc module in your Python script and use the connection string to establish a connection to the database.

import pyodbc

server = '{server name}.database.windows.net'
database = '{database name}'
username = '{username}'
password = '{password}'
driver= '{ODBC Driver 17 for SQL Server}'

cnxn = pyodbc.connect('DRIVER=' + driver + ';SERVER=' + server + ';PORT=1433;DATABASE=' + database + ';UID=' + username + ';PWD=' + password)

6. Once you have established a connection, you can create a cursor object to execute SQL queries.

cursor = cnxn.cursor()

cursor.execute("SELECT * FROM {table name}")

for row in cursor:
print(row)

7. Close the connection once you are done.

cnxn.close()

Conclusion

In this lab, we have discussed how to connect to an Azure SQL Database using Python. You can now use this knowledge to interact with your database and execute queries.