Skip to content

Latest commit

 

History

History
75 lines (55 loc) · 3.59 KB

sql-database-connect-query-python.md

File metadata and controls

75 lines (55 loc) · 3.59 KB
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

Quickstart: Use Python to query an Azure SQL database

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.

Prerequisites

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.

SQL server connection information

[!INCLUDE prerequisites-server-connection-info]

Insert code to query SQL database

  1. In your favorite text editor, create a new file, sqltest.py.

  2. 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()

Run the code

  1. At the command prompt, run the following commands:

    python sqltest.py
  2. Verify that the top 20 rows are returned and then close the application window.

Next steps