Python Connect to Azure SQL Database

This article will discuss the quick steps to connect to the Azure SQL database using Python.

How to connect to Azure SQL database using Python

You can easily connect to the Azure SQL database using Python using the instructions below.

As a prerequisite, you need the below stuff

  • You must have an Azure Account. You can create an Azure Free account now if you don’t have an Azure Account.
  • You must have a database.
  • You must install Python and the other dependencies.

Open your favorite text editor and name it test.py.

Now add the below script to that file.

import pyodbc
myserver = '<yourservername>.database.windows.net'
databasenm = '<yourdatabasename>'
username = '<username>'
password = '<password>'   
driverdetails= '{ODBC Driver 17 for SQL Server}'

with pyodbc.connect('DRIVER='+driverdetails+';SERVER='+myserver+';PORT=1433;DATABASE='+databasenm+';UID='+username+';PWD='+ password) as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT TOP 4 name FROM sys.databases")
        row = cursor.fetchone()
        while row:
            print (str(row[0]) + " " + str(row[1]))
            row = cursor.fetchone()
  • Now, open the command prompt and run the below command to run the above script
python test.py

You may also like following the articles below

Conclusion

This article discussed how to connect to the Azure SQL database using Python. Thanks for reading this article !!!