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

在本快速入门中,我们使用 Node.js 连接到 Azure SQL 数据库,并使用 T-SQL 语句来查询数据。In this quickstart, you use Node.js to connect to an Azure SQL database and use T-SQL statements to query data.

必备条件Prerequisites


重要

本文中脚本的编写目的是使用 Adventure Works 数据库。The scripts in this article are written to use the Adventure Works database.

备注

可以选择使用 Azure SQL 托管实例。You can optionally choose to use an Azure SQL managed instance.

若要执行创建和配置操作,请使用 Azure 门户PowerShellCLI,然后设置现场VM 连接性。To create and configure, use the Azure Portal, PowerShell, or CLI, then setup on-site or VM connectivity.

若要加载数据,请参阅通过 BACPAC 进行还原(使用 Adventure Works 文件),或参阅还原 Wide World Importers 数据库To load data, see restore with BACPAC with the Adventure Works file, or see restore the Wide World Importers database.

获取 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 托管实例”页。 Go 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.

创建项目Create the project

打开命令提示符,并创建一个名为 sqltest 的文件夹。Open a command prompt and create a folder named sqltest. 打开已创建的文件夹,并运行以下命令:Open the folder you created and run the following command:

npm init -y
npm install tedious

添加用于查询数据库的代码Add code to query database

  1. 在喜欢的文本编辑器中,创建新文件 sqltest.jsIn your favorite text editor, create a new file, sqltest.js.

  2. 将其内容替换为以下代码。Replace its contents with the following code. 然后,为服务器、数据库、用户和密码添加相应的值。Then add the appropriate values for your server, database, user, and password.

    const { Connection, Request } = require("tedious");
    
    // Create connection to database
    const config = {
      authentication: {
        options: {
          userName: "username", // update me
          password: "password" // update me
        },
        type: "default"
      },
      server: "your_server.database.chinacloudapi.cn", // update me
      options: {
        database: "your_database", //update me
        encrypt: true
      }
    };
    
    const connection = new Connection(config);
    
    // Attempt to connect and execute queries if connection goes through
    connection.on("connect", err => {
      if (err) {
        console.error(err.message);
      } else {
        queryDatabase();
      }
    });
    
    function queryDatabase() {
      console.log("Reading rows from the Table...");
    
      // Read all rows from table
      const request = new Request(
        `SELECT TOP 20 pc.Name as CategoryName,
                       p.name as ProductName
         FROM [SalesLT].[ProductCategory] pc
         JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid`,
        (err, rowCount) => {
          if (err) {
            console.error(err.message);
          } else {
            console.log(`${rowCount} row(s) returned`);
          }
        }
      );
    
      request.on("row", columns => {
        columns.forEach(column => {
          console.log("%s\t%s", column.metadata.colName, column.value);
        });
      });
    
      connection.execSql(request);
    }
    

备注

代码示例使用适用于 Azure SQL 的 AdventureWorksLT 示例数据库。The code example uses the AdventureWorksLT sample database for Azure SQL.

运行代码Run the code

  1. 在命令提示符下运行此程序。At the command prompt, run the program.

    node sqltest.js
    
  2. 验证是否已返回前 20 行,然后关闭应用程序窗口。Verify the top 20 rows are returned and close the application window.

后续步骤Next steps