| title | Use Python to query a database |
|---|---|
| description | This topic shows you how to use Python to create a program that connects to a database in Azure SQL Database and query it using Transact-SQL statements. |
| titleSuffix | Azure SQL Database & SQL Managed Instance |
| services | sql-database |
| ms.service | sql-database |
| ms.subservice | development |
| ms.custom | seo-python-october2019, sqldbrb=2, devx-track-python |
| ms.devlang | python |
| ms.topic | quickstart |
| author | stevestein |
| ms.author | sstein |
| ms.reviewer | |
| ms.date | 12/19/2020 |
[!INCLUDEappliesto-sqldb-sqlmi]
In this quickstart, you use Python to connect to Azure SQL Database, Azure SQL Managed Instance, or Synapse SQL database and use T-SQL statements to query data.
To complete this quickstart, you need:
-
An Azure account with an active subscription. Create an account for free.
-
A database where you will run a query.
[!INCLUDEcreate-configure-database]
-
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.
To install Python and other required packages, use
sudo apt-get install python python-pip gcc g++ build-essential.To install the ODBC driver, SQLCMD, and the Python driver for SQL Server, see configure an environment for pyodbc Python development.
For further information, see Microsoft ODBC driver on Linux.
To install Python, the ODBC driver and SQLCMD, and the Python driver for SQL Server, see configure an environment for pyodbc Python development.
For further information, see Microsoft ODBC driver.
To further explore Python and the database in Azure SQL Database, see Azure SQL Database libraries for Python, the pyodbc repository, and a pyodbc sample.
-
In a text editor, create a new file named sqltest.py.
-
Add the following code. Get the connection information from the prerequisites section and substitute your own values for <server>, <database>, <username>, and <password>.
import pyodbc server = '<server>.database.windows.net' database = '<database>' username = '<username>' password = '<password>' driver= '{ODBC Driver 17 for SQL Server}' with pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn: with conn.cursor() as cursor: cursor.execute("SELECT TOP 3 name, collation_name FROM sys.databases") row = cursor.fetchone() while row: print (str(row[0]) + " " + str(row[1])) row = cursor.fetchone()
-
At a command prompt, run the following command:
python sqltest.py
-
Verify that the databases and their collations are returned, and then close the command window.