Quickstart: Use Python to query an Azure SQL database
In this quickstart, you use Python to connect to an Azure SQL database and use T-SQL statements to query data.
Prerequisites
An Azure account with an active subscription. Create an account for free.
Python 3 and related software
To install Homebrew and Python, the ODBC driver and SQLCMD, and the Python driver for SQL Server, use steps 1.2, 1.3, and 2.1 in create Python apps using SQL Server on macOS.
For further information, see Microsoft ODBC Driver on macOS.
Important
The scripts in this article are written to use the Adventure Works database.
Note
You can optionally choose to use an Azure SQL managed instance.
To create and configure, use the Azure Portal, PowerShell, or CLI, then setup on-site or VM connectivity.
To load data, see restore with BACPAC with the Adventure Works file, or see restore the Wide World Importers database.
To further explore Python and the Azure SQL database, see Azure SQL database libraries for Python, the pyodbc repository, and a pyodbc sample.
Get SQL server connection information
Get the connection information you need to connect to the Azure SQL database. You'll need the fully qualified server name or host name, database name, and login information for the upcoming procedures.
Sign in to the Azure portal.
Go to the SQL databases or SQL managed instances page.
On the Overview page, review the fully qualified server name next to Server name for a single database or the fully qualified server name next to Host for a managed instance. To copy the server name or host name, hover over it and select the Copy icon.
Create code to query your SQL database
In a text editor, create a new file named sqltest.py.
Add the following code. Substitute your own values for <server>, <database>, <username>, and <password>.
Important
The code in this example uses the sample AdventureWorksLT data, which you can choose as source when creating your database. If your database has different data, use tables from your own database in the SELECT query.
import pyodbc server = '<server>.database.windows.net' database = '<database>' 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) cursor = cnxn.cursor() cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid") row = cursor.fetchone() while row: print (str(row[0]) + " " + str(row[1])) row = cursor.fetchone()
Run the code
At a command prompt, run the following command:
python sqltest.pyVerify that the top 20 Category/Product rows are returned, then close the command window.
Next steps
Feedback
Loading feedback...




