查询数据库

跳转到内容

文档索引
在此获取完整文档索引:/d1/llms.txt
在进一步探索之前,可使用该文件发现所有可用页面。

查询数据库

最后更新:2026年4月21日|复制为 Markdown|查看 Markdown 原文|Agent setup

D1 与大多数 SQLite 的 SQL 约定兼容,因为它利用了 SQLite 的查询引擎。你可以使用 SQL 命令来查询 D1。

有多种方式可以与 D1 数据库交互:

  1. 在代码中使用 D1 Workers Binding API。
  2. 使用 D1 REST API。
  3. 使用 D1 Wrangler 命令。

使用 SQL 查询 D1

D1 理解 SQLite 语义,这使你能够通过 Workers BindingAPI 或 REST API(包括 Wrangler 命令)使用 SQL 语句查询数据库。参阅 D1 SQL API 以了解有关受支持 SQL 语句的更多信息。

使用外键关系

在 D1 中使用 SQL 时,你可能希望在数据库的各表之间定义并强制执行外键约束。外键约束允许你强制实施跨表的关系,或阻止你删除引用了其他表中行的行。下面展示了一个外键关系的示例。

CREATE TABLE users (
    user_id INTEGER PRIMARY KEY,
    email_address TEXT,
    name TEXT,
    metadata TEXT
)

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    status INTEGER,
    item_desc TEXT,
    shipped_date INTEGER,
    user_who_ordered INTEGER,
    FOREIGN KEY(user_who_ordered) REFERENCES users(user_id)
)

参阅 Define foreign keys 以获取更多信息。

查询 JSON

D1 允许你查询并解析存储在数据库中的 JSON 数据。例如,你可以提取 JSON 对象中的某个值。

给定一个名为 sensor_reading 的列中的以下 JSON 对象(type:blob),你可以直接从其中提取值。

{
    "measurement": {
        "temp_f": "77.4",
        "aqi": [21, 42, 58],
        "o3": [18, 500],
        "wind_mph": "13",
        "location": "US-NY"
    }
}
-- Extract the temperature value
SELECT json_extract(sensor_reading, '$.measurement.temp_f')-- returns "77.4" as TEXT

参阅 Query JSON 以了解有关查询 JSON 对象的更多信息。

使用 Workers Binding API 查询 D1

Workers Binding API 主要与数据平面(data plane)交互,允许你从 Worker 中查询 D1 数据库。

这要求你:

  1. 将 D1 数据库绑定到你的 Worker。
  2. 准备一条语句。
  3. 运行该语句。

index.jsjs

export default {
    async fetch(request, env) {
        const {pathname} = new URL(request.url);
        const companyName1 = `Bs Beverages`;
        const companyName2 = `Around the Horn`;
        const stmt = env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`);

        if (pathname === `/RUN`) {
            const returnValue = await stmt.bind(companyName1).run();
            return Response.json(returnValue);
        }

        return new Response(
            `Welcome to the D1 API Playground!
						\nChange the URL to test the various methods inside your index.js file.`,
        );
    },
};

参阅 Workers Binding API 以获取更多信息。

使用 REST API 查询 D1

REST API 主要与控制平面(control plane)交互,允许你创建/管理 D1 数据库。

参阅 D1 REST API 以获取 D1 REST API 文档。

使用 Wrangler 命令查询 D1

你可以使用 Wrangler 命令查询 D1 数据库。请注意,Wrangler 命令使用 REST API 来执行其操作。

npx wrangler d1 execute prod-d1-tutorial --command="SELECT * FROM Customers"
🌀 Mapping SQL input into an array of statements
🌀 Executing on local database production-db-backend (<DATABASE_ID>) from .wrangler/state/v3/d1:
┌────────────┬─────────────────────┬───────────────────┐
│ CustomerId │ CompanyName         │ ContactName       │
├────────────┼─────────────────────┼───────────────────┤
│ 1          │ Alfreds Futterkiste │ Maria Anders      │
├────────────┼─────────────────────┼───────────────────┤
│ 4          │ Around the Horn     │ Thomas Hardy      │
├────────────┼─────────────────────┼───────────────────┤
│ 11         │ Bs Beverages        │ Victoria Ashworth │
├────────────┼─────────────────────┼───────────────────┤
│ 13         │ Bs Beverages        │ Random Name       │
└────────────┴─────────────────────┴───────────────────┘