title | description | services | ms.service | ms.subservice | ms.custom | ms.devlang | ms.topic | author | ms.author | ms.reviewer | manager | ms.date |
---|---|---|---|---|---|---|---|---|---|---|---|---|
Use Python to query Azure SQL Database | Microsoft Docs |
This topic shows you how to use Python to create a program that connects to an Azure SQL Database and query it using Transact-SQL statements. |
sql-database |
sql-database |
development |
python |
quickstart |
CarlRabeler |
carlrab |
craigg |
11/01/2018 |
This quickstart demonstrates how to use Python to connect to an Azure SQL database and use Transact-SQL statements to query data. For further sdk details, checkout our reference documentation, a pyodbc sample, and the pyodbc GitHub repository.
To complete this quickstart, make sure you have the following:
[!INCLUDE prerequisites-create-db]
-
A server-level firewall rule for the public IP address of the computer you use for this quickstart.
-
You have installed Python and related software for your operating system:
- MacOS: Install Homebrew and Python, install the ODBC driver and SQLCMD, and then install the Python Driver for SQL Server. See Steps 1.2, 1.3, and 2.1.
- Ubuntu: Install Python and other required packages, and then install the Python Driver for SQL Server. See Steps 1.2, 1.3, and 2.1.
- Windows: Install the newest version of Python (environment variable is now configured for you), install the ODBC driver and SQLCMD, and then install the Python Driver for SQL Server. See Step 1.2, 1.3, and 2.1.
[!INCLUDE prerequisites-server-connection-info]
-
In your favorite text editor, create a new file, sqltest.py.
-
Replace the contents with the following code and add the appropriate values for your server, database, user, and password.
import pyodbc
server = 'your_server.database.windows.net'
database = 'your_database'
username = 'your_username'
password = 'your_password'
driver= '{ODBC Driver 13 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()
-
At the command prompt, run the following commands:
python sqltest.py
-
Verify that the top 20 rows are returned and then close the application window.