Skip to content

快速入门:将 数据墙DBW 与关系型数据库搭配使用

在本快速入门中,你将使用 数据墙DBW为本地 SQL 数据库创建 REST 和 GraphQL 终结点。请选择你的数据库引擎开始。

先决条件

安装 数据墙DBW CLI

从 NuGet 将 Microsoft.DataApiBuilder 包安装为 .NET 工具。

  1. 使用 dotnet tool install 并配合 --global 参数安装最新版 Microsoft.DataApiBuilder

    bash
    dotnet tool install --global Microsoft.DataApiBuilder

    NOTE

    如果该包已经安装,请改用 dotnet tool update 更新。

    bash
    dotnet tool update --global Microsoft.DataApiBuilder
  2. 使用带 --global 参数的 dotnet tool list 验证工具是否已安装。

    bash
    dotnet tool list --global

拉取数据库镜像

TIP

已经有数据库了? 请跳到创建并填充数据库,针对你的引擎运行 SQL 脚本,然后使用你自己的连接字符串跳到配置 数据墙DBW

下载适用于你的数据库引擎的 Docker 镜像。根据你的网络速度,此步骤可能需要几分钟。

SQL Server

shell
docker pull mcr.microsoft.com/mssql/server:2025-latest

PostgreSQL

shell
docker pull postgres:16

MySQL

shell
docker pull mysql:8

启动数据库

在 Docker 中运行本地数据库实例。

SQL Server

shell
docker run --name dab-mssql --env "ACCEPT_EULA=Y" --env "MSSQL_SA_PASSWORD=P@ssw0rd1" --publish 1433:1433 --detach mcr.microsoft.com/mssql/server:2025-latest

TIP

如果端口 1433 已被占用(例如被本地 SQL Server 安装占用),请将 --publish 改成其他主机端口,例如 1434:1433,并在后续步骤中将 Server=localhost,1433 更新为 Server=localhost,1434

在运行下一条命令前,验证数据库引擎是否已准备就绪。

shell
docker exec dab-mssql /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "P@ssw0rd1" -C -Q "SELECT 1"

如果返回错误,请等待几秒后重试。

PostgreSQL

shell
docker run --name dab-postgres --env "POSTGRES_PASSWORD=P@ssw0rd1" --publish 5432:5432 --detach postgres:16

MySQL

shell
docker run --name dab-mysql --env "MYSQL_ROOT_PASSWORD=P@ssw0rd1" --publish 3306:3306 --detach mysql:8

在运行下一条命令前,验证数据库引擎是否已准备就绪。

shell
docker exec dab-mysql mysql -uroot -pP@ssw0rd1 -e "SELECT 1"

如果返回错误,请等待几秒后重试。

创建并填充数据库

创建 todos 数据库和表,然后添加示例数据。如果你使用 Docker,则不需要 SQL 客户端,docker exec 会直接在容器内运行命令。如果你使用自己的数据库,请在你偏好的工具中运行 SQL 脚本。

SQL Server

  1. 创建数据库。

    shell
    docker exec dab-mssql /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "P@ssw0rd1" -C -Q "CREATE DATABASE todos;"
  2. 创建表并添加示例数据。

    shell
    docker exec dab-mssql /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "P@ssw0rd1" -C -d todos -Q "CREATE TABLE dbo.todos (id int PRIMARY KEY, title nvarchar(100) NOT NULL, completed bit NOT NULL DEFAULT 0); INSERT INTO dbo.todos VALUES (1, 'Walk the dog', 0), (2, 'Feed the fish', 0), (3, 'Comb the cat', 1);"

TIP

使用你自己的 SQL Server? 直接运行以下脚本:

sql
CREATE DATABASE todos;
GO
USE todos;
GO
CREATE TABLE dbo.todos (id int PRIMARY KEY, title nvarchar(100) NOT NULL, completed bit NOT NULL DEFAULT 0);
INSERT INTO dbo.todos VALUES (1, 'Walk the dog', 0), (2, 'Feed the fish', 0), (3, 'Comb the cat', 1);

PostgreSQL

  1. 创建数据库。

    shell
    docker exec dab-postgres psql -U postgres -c "CREATE DATABASE todos;"
  2. 创建表并添加示例数据。

    shell
    docker exec dab-postgres psql -U postgres -d todos -c "CREATE TABLE todos (id int PRIMARY KEY, title varchar(100) NOT NULL, completed boolean NOT NULL DEFAULT false); INSERT INTO todos VALUES (1, 'Walk the dog', false), (2, 'Feed the fish', false), (3, 'Comb the cat', true);"

TIP

使用你自己的 PostgreSQL 服务器? 直接运行以下脚本:

sql
CREATE DATABASE todos;
\c todos
CREATE TABLE todos (id int PRIMARY KEY, title varchar(100) NOT NULL, completed boolean NOT NULL DEFAULT false);
INSERT INTO todos VALUES (1, 'Walk the dog', false), (2, 'Feed the fish', false), (3, 'Comb the cat', true);

MySQL

  1. 创建数据库。

    shell
    docker exec dab-mysql mysql -uroot -pP@ssw0rd1 -e "CREATE DATABASE todos;"
  2. 创建表并添加示例数据。

    shell
    docker exec dab-mysql mysql -uroot -pP@ssw0rd1 -e "USE todos; CREATE TABLE todos (id int PRIMARY KEY, title varchar(100) NOT NULL, completed bool NOT NULL DEFAULT false); INSERT INTO todos VALUES (1, 'Walk the dog', false), (2, 'Feed the fish', false), (3, 'Comb the cat', true);"

TIP

使用你自己的 MySQL 服务器? 直接运行以下脚本:

sql
CREATE DATABASE todos;
USE todos;
CREATE TABLE todos (id int PRIMARY KEY, title varchar(100) NOT NULL, completed bool NOT NULL DEFAULT false);
INSERT INTO todos VALUES (1, 'Walk the dog', false), (2, 'Feed the fish', false), (3, 'Comb the cat', true);

配置 数据墙DBW

创建一个 数据墙DBW 配置文件,并添加 Todo 实体。

TIP

使用你自己的数据库? 请将 dab init 中的连接字符串替换为你自己的:

  • SQL Server: Server=<host>,<port>;Database=todos;User Id=<user>;Password=<password>;TrustServerCertificate=true;Encrypt=true;
  • PostgreSQL: Host=<host>;Port=5432;Database=todos;User ID=<user>;Password=<password>;
  • MySQL: Server=<host>;Port=3306;Database=todos;User=<user>;Password=<password>;

SQL Server

  1. 初始化配置。

    bash
    dab init --database-type "mssql" --host-mode "Development" --connection-string "Server=localhost,1433;Database=todos;User Id=sa;Password=P@ssw0rd1;TrustServerCertificate=true;Encrypt=true;"
  2. 添加 Todo 实体。

    bash
    dab add Todo --source "dbo.todos" --permissions "anonymous:*"

PostgreSQL

  1. 初始化配置。

    bash
    dab init --database-type "postgresql" --host-mode "Development" --connection-string "Host=localhost;Port=5432;Database=todos;User ID=postgres;Password=P@ssw0rd1;"
  2. 添加 Todo 实体。

    bash
    dab add Todo --source "public.todos" --permissions "anonymous:*"

MySQL

  1. 初始化配置。

    bash
    dab init --database-type "mysql" --host-mode "Development" --connection-string "Server=localhost;Port=3306;Database=todos;User=root;Password=P@ssw0rd1;"
  2. 添加 Todo 实体。

    bash
    dab add Todo --source "todos" --permissions "anonymous:*"

你的 dab-config.json 文件现在应类似于以下示例:

SQL Server

json
{
  "$schema": "https://github.com/Azure/data-api-builder/releases/download/v1.7.0/dab.draft.schema.json",
  "data-source": {
    "database-type": "mssql",
    "connection-string": "Server=localhost,1433;Database=todos;User Id=sa;Password=P@ssw0rd1;TrustServerCertificate=true;Encrypt=true;"
  },
  "runtime": {
    "rest": {
      "enabled": true
    },
    "graphql": {
      "enabled": true
    },
    "host": {
      "mode": "development",
      "cors": {
        "origins": ["*"]
      }
    }
  },
  "entities": {
    "Todo": {
      "source": "dbo.todos",
      "permissions": [
        {
          "role": "anonymous",
          "actions": [
            "*"
          ]
        }
      ]
    }
  }
}

PostgreSQL

json
{
  "$schema": "https://github.com/Azure/data-api-builder/releases/download/v1.7.0/dab.draft.schema.json",
  "data-source": {
    "database-type": "postgresql",
    "connection-string": "Host=localhost;Port=5432;Database=todos;User ID=postgres;Password=P@ssw0rd1;"
  },
  "runtime": {
    "rest": {
      "enabled": true
    },
    "graphql": {
      "enabled": true
    },
    "host": {
      "mode": "development",
      "cors": {
        "origins": ["*"]
      }
    }
  },
  "entities": {
    "Todo": {
      "source": "public.todos",
      "permissions": [
        {
          "role": "anonymous",
          "actions": [
            "*"
          ]
        }
      ]
    }
  }
}

MySQL

json
{
  "$schema": "https://github.com/Azure/data-api-builder/releases/download/v1.7.0/dab.draft.schema.json",
  "data-source": {
    "database-type": "mysql",
    "connection-string": "Server=localhost;Port=3306;Database=todos;User=root;Password=P@ssw0rd1;"
  },
  "runtime": {
    "rest": {
      "enabled": true
    },
    "graphql": {
      "enabled": true
    },
    "host": {
      "mode": "development",
      "cors": {
        "origins": ["*"]
      }
    }
  },
  "entities": {
    "Todo": {
      "source": "todos",
      "permissions": [
        {
          "role": "anonymous",
          "actions": [
            "*"
          ]
        }
      ]
    }
  }
}

TIP

你可以跳过 dab initdab add 命令,直接按这里展示的内容创建 dab-config.json 文件。

启动 API

使用 dab start 运行该工具,并为你的实体创建 API 终结点。

bash
dab start

输出中应包含正在运行的 API 地址。

text
      Successfully completed runtime initialization.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: <http://localhost:5000>

TIP

在本示例中,应用运行在 localhost5000 端口。你实际运行的应用可能使用不同的地址和端口。

测试 API

  1. 打开浏览器并导航到 Todo 实体的 REST 终结点。

    text
    http://localhost:5000/api/Todo
  2. JSON 响应应包含全部三个待办事项。

    json
    {
      "value": [
        { "id": 1, "title": "Walk the dog", "completed": false },
        { "id": 2, "title": "Feed the fish", "completed": false },
        { "id": 3, "title": "Comb the cat", "completed": true }
      ]
    }
  3. 打开位于 /swagger 的 Swagger 文档页。

    text
    http://localhost:5000/swagger

构建一个 Web 应用

使用纯 HTML 文件在浏览器中显示你的 todos。创建一个名为 todo.html 的文件,并使用 REST 或 GraphQL 终结点之一。

REST

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Todo App</title>
  <style>
    body { font-family: sans-serif; max-width: 400px; margin: 2rem auto; }
    li.done { text-decoration: line-through; color: gray; }
    #error { color: red; }
  </style>
</head>
<body>
  <h1>Todos</h1>
  <ul id="list"></ul>
  <p id="error"></p>
  <script>
    fetch('http://localhost:5000/api/Todo')
      .then(r => r.json())
      .then(data => {
        const ul = document.getElementById('list');
        data.value.forEach(todo => {
          const li = document.createElement('li');
          li.textContent = todo.title;
          if (todo.completed) li.className = 'done';
          ul.appendChild(li);
        });
      })
      .catch(() => {
        document.getElementById('error').textContent =
          'Could not reach the API. Make sure 数据墙DBW is running on http://localhost:5000.';
      });
  </script>
</body>
</html>

GraphQL

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Todo App</title>
  <style>
    body { font-family: sans-serif; max-width: 400px; margin: 2rem auto; }
    li.done { text-decoration: line-through; color: gray; }
    #error { color: red; }
  </style>
</head>
<body>
  <h1>Todos</h1>
  <ul id="list"></ul>
  <p id="error"></p>
  <script>
    fetch('http://localhost:5000/graphql', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query: '{ todos { items { id title completed } } }' })
    })
      .then(r => r.json())
      .then(data => {
        const ul = document.getElementById('list');
        data.data.todos.items.forEach(todo => {
          const li = document.createElement('li');
          li.textContent = todo.title;
          if (todo.completed) li.className = 'done';
          ul.appendChild(li);
        });
      })
      .catch(() => {
        document.getElementById('error').textContent =
          'Could not reach the API. Make sure 数据墙DBW is running on http://localhost:5000.';
      });
  </script>
</body>
</html>

在浏览器中打开 todo.html。页面会获取全部待办事项并将其渲染为列表,已完成项会以删除线显示。

IMPORTANT

你配置中的 cors 设置允许这个从本地文件系统打开的 HTML 文件调用 API。没有它,浏览器会阻止该请求。

清理

完成后,停止并删除 Docker 容器。

SQL Server

shell
docker stop dab-mssql && docker rm dab-mssql

PostgreSQL

shell
docker stop dab-postgres && docker rm dab-postgres

MySQL

shell
docker stop dab-mysql && docker rm dab-mysql

下一步

TIP

下一步建议阅读:REST 终结点

数据墙DBW 产品文档与开发指南。