Hướng dẫn javascript connect to database - javascript kết nối với cơ sở dữ liệu

Chuyển đến nội dung chính

Trình duyệt này không còn được hỗ trợ nữa.

Hãy nâng cấp lên Microsoft Edge để tận dụng các tính năng mới nhất, bản cập nhật bảo mật và hỗ trợ kỹ thuật.

Quickstart: Use Node.js to query a database in Azure SQL Database or Azure SQL Managed Instance

  • Bài viết
  • 10/27/2022
  • 3 phút để đọc

Trong bài viết này

Applies to: Azure SQL Database Azure SQL Managed Instance

Hướng dẫn javascript connect to database - javascript kết nối với cơ sở dữ liệu
Azure SQL Database Azure SQL Managed Instance

In this quickstart, you use Node.js to connect to a database and query data.

Prerequisites

To complete this quickstart, you need:

  • An Azure account with an active subscription. Create an account for free.

    ActionSQL DatabaseSQL Managed InstanceSQL Server on Azure VM
    Create Portal Portal Portal
    CLI CLI
    PowerShell PowerShell PowerShell
    Configure Server-level IP firewall rule Connectivity from a VM
    Connectivity from on-premises Connect to a SQL Server instance
    Load data Adventure Works loaded per quickstart Restore Wide World Importers Restore Wide World Importers
    Restore or import Adventure Works from a BACPAC file from GitHub Restore or import Adventure Works from a BACPAC file from GitHub
  • Node.js-related software


Important

The scripts in this article are written to use the Adventure Works database.Adventure Works database.

Get server connection information

Get the connection information you need to connect to the database in Azure SQL Database. You'll need the fully qualified server name or host name, database name, and login information for the upcoming procedures.

  1. Sign in to the Azure portal.

  2. Go to the SQL Databases or SQL Managed Instances page.SQL Databases or SQL Managed Instances page.

  3. On the Overview page, review the fully qualified server name next to Server name for a database in Azure SQL Database or the fully qualified server name (or IP address) next to Host for an Azure SQL Managed Instance or SQL Server on Azure VM. To copy the server name or host name, hover over it and select the Copy icon.Overview page, review the fully qualified server name next to Server name for a database in Azure SQL Database or the fully qualified server name (or IP address) next to Host for an Azure SQL Managed Instance or SQL Server on Azure VM. To copy the server name or host name, hover over it and select the Copy icon.

Create the project

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

Thêm mã để truy vấn cơ sở dữ liệu

  1. Trong trình soạn thảo văn bản yêu thích của bạn, hãy tạo một tệp mới, sqltest.js.

  2. Thay thế nội dung của nó bằng mã sau.Sau đó thêm các giá trị phù hợp cho máy chủ, cơ sở dữ liệu, người dùng và mật khẩu của bạn.

    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.windows.net", // update me
      options: {
        database: "your_database", //update me
        encrypt: true
      }
    };
    
    /* 
        //Use Azure VM Managed Identity to connect to the SQL database
        const config = {
            server: process.env["db_server"],
            authentication: {
                type: 'azure-active-directory-msi-vm',
            },
            options: {
                database: process.env["db_database"],
                encrypt: true,
                port: 1433
            }
        };
    
        //Use Azure App Service Managed Identity to connect to the SQL database
        const config = {
            server: process.env["db_server"],
            authentication: {
                type: 'azure-active-directory-msi-app-service',
            },
            options: {
                database: process.env["db_database"],
                encrypt: true,
                port: 1433
            }
        };
    
    */
    
    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();
      }
      connection.close();
    });
    
    connection.connect();
    
    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);
    }
    

Ghi chú

Ví dụ mã sử dụng cơ sở dữ liệu mẫu AdventureWorkslt trong cơ sở dữ liệu Azure SQL.AdventureWorksLT sample database in Azure SQL Database.

Chạy mã

  1. Tại dấu nhắc lệnh, chạy chương trình.

    node sqltest.js
    
  2. Xác minh 20 hàng hàng đầu được trả về và đóng cửa sổ ứng dụng.

Bước tiếp theo

  • Trình điều khiển Microsoft Node.js cho SQL Server

  • Kết nối và truy vấn trên Windows/Linux/MacOS với .NET Core, Visual Studio Code hoặc SSMS (chỉ Windows)

  • Bắt đầu với .NET Core trên Windows/Linux/MacOS bằng dòng lệnh

  • Thiết kế cơ sở dữ liệu đầu tiên của bạn trong cơ sở dữ liệu Azure SQL bằng cách sử dụng .NET hoặc SSMS

Phản HồI

Gửi và xem ý kiến ph