您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用 Python 查询 Azure SQL 数据库Quickstart: Use Python to query an Azure SQL database

本快速入门演示了如何使用 Python 连接到 Azure SQL 数据库,然后使用 Transact-SQL 语句查询数据。This quickstart demonstrates how to use Python to connect to an Azure SQL database and use Transact-SQL statements to query data. 如需进一步的 SDK 详细信息,请查看参考文档、pyodbc GitHub 存储库以及 pyodbc 示例For further SDK details, check out our reference documentation, the pyodbc GitHub repository, and a pyodbc sample.

先决条件Prerequisites

若要完成本快速入门,请确保符合以下条件:To complete this quickstart, make sure you have the following:

获取 SQL Server 连接信息Get SQL server connection information

获取连接到 Azure SQL 数据库所需的连接信息。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.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 导航到“SQL 数据库”或“SQL 托管实例”页。Navigate to the SQL databases or SQL managed instances page.

  3. 在“概览”页中,查看单一数据库的“服务器名称”旁边的完全限定的服务器名称,或者托管实例的“主机”旁边的完全限定的服务器名称。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.

创建用于查询 SQL 数据库的代码Create code to query your SQL database

  1. 在文本编辑器中,创建新文件 sqltest.py。In a text editor, create a new file named sqltest.py.

  2. 添加以下代码。Add the following code. 将自己的值替换为 <服务器>、<数据库>、<用户名> 和 <密码>。Substitute your own values for <server>, <database>, <username>, and <password>.

    重要

    本示例中的代码使用示例 AdventureWorksLT 数据,在创建数据库时可以选择该数据作为源。The code in this example uses the sample AdventureWorksLT data, which you can choose as source when creating your database. 如果数据库有不同数据,请在 SELECT 查询中使用自己数据库中的表。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

  1. 请在命令提示符处运行以下命令:At a command prompt, run the following command:

    python sqltest.py
    
  2. 确认已返回前 20 个类别/产品行,然后关闭命令窗口。Verify that the top 20 Category/Product rows are returned, then close the command window.

后续步骤Next steps