从 Hono 查询 D1

跳转到内容

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

从 Hono 查询 D1

从 Hono Web 框架查询 D1

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

Hono 是一个用于构建 API 优先应用的快速 Web 框架,它对 Workers 和 Pages 都提供一流的支持。

使用 Workers 时:

如果你使用的是 Pages Functions:

  1. 将 D1 数据库绑定到你的 Pages Function。
  2. 在本地开发时,向 wrangler dev 传入 --d1 BINDING_NAME=DATABASE_ID 标志。BINDING_NAME 应与你在代码中调用的一致,DATABASE_ID 应与你在 Wrangler 配置文件中定义的 database_id 一致:例如,--d1 DB=xxxx-xxxx-xxxx-xxxx-xxxx。
  3. 有关 Cloudflare Pages ↗︎ 的内容,请参阅 Hono 指南。

以下示例展示了如何从 Workers 脚本和 Pages Function 中访问绑定到 DB 的 D1 数据库:

import { Hono } from "hono";

// This ensures c.env.DB is correctly typed
type Bindings = {
	DB: D1Database;
};

const app = new Hono<{ Bindings: Bindings }>();

// Accessing D1 is via the c.env.YOUR_BINDING property
app.get("/query/users/:id", async (c) => {
	const userId = c.req.param("id");
	try {
		let { results } = await c.env.DB.prepare(
			"SELECT * FROM users WHERE user_id = ?",
		)
			.bind(userId)
			.run();
		return c.json(results);
	} catch (e) {
		return c.json({ err: "Failed to query user" }, 500);
	}
});

// Export our Hono app: Hono automatically exports a
// Workers 'fetch' handler for you
export default app;
import { Hono } from "hono";
import { handle } from "hono/cloudflare-pages";

// This ensures c.env.DB is correctly typed
type Bindings = {
	DB: D1Database;
};

const app = new Hono<{ Bindings: Bindings }>().basePath("/api");

// Accessing D1 is via the c.env.YOUR_BINDING property
app.get("/query/users/:id", async (c) => {
	const userId = c.req.param("id");
	try {
		let { results } = await c.env.DB.prepare(
			"SELECT * FROM users WHERE user_id = ?",
		)
			.bind(userId)
			.run();
		return c.json(results);
	} catch (e) {
		return c.json({ err: "Failed to query user" }, 500);
	}
});

// Export the Hono instance as a Pages onRequest function
export const onRequest = handle(app);