以下内容参考了

https://developers.cloudflare.com/d1/get-started/
https://developers.cloudflare.com/d1/examples/d1-and-hono/
  • 1.
  • 2.

1:登录

npx wrangler login
  • 1.

2:创建Worker

npm create cloudflare@latest d1-tutorial
  • 1.

Choose "Hello World" Worker for the type of application.
Select yes to using TypeScript.
Select no to deploying.

3:创建数据库

npx wrangler d1 create prod-d1-tutorial
  • 1.

4:绑定数据库

cd d1-tutorial
nano wrangler.toml
  • 1.
  • 2.

在末尾添加

[[d1_databases]]
binding = "DB"
database_name = "prod-d1-tutorial"
database_id = "<unique-ID-for-your-database>"
  • 1.
  • 2.
  • 3.
  • 4.

5:导入测试数据

将下面代码保存成schema.sql

DROP TABLE IF EXISTS Customers;
CREATE TABLE IF NOT EXISTS Customers (CustomerId INTEGER PRIMARY KEY, CompanyName TEXT, ContactName TEXT);
INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders'), (4, 'Around the Horn', 'Thomas Hardy'), (11, 'Bs Beverages', 'Victoria Ashworth'), (13, 'Bs Beverages', 'Random Name');
  • 1.
  • 2.
  • 3.

然后用下面代码导入

npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql
  • 1.

6:安装依赖库

npm i hono
  • 1.

7:修改代码

echo ''> src/index.ts
nano src/index.ts
  • 1.
  • 2.

贴入下面代码

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("/api/beverages/:id", async (c) => {
  const customerID = c.req.param("id");
  try {
    let { results } = await c.env.DB.prepare(
      "SELECT * FROM Customers WHERE CustomerID = ?",
    )
      .bind(customerID)
      .all();
    return c.json(results);
  } catch (e) {
    return c.json({ err: e.message }, 500);
  }
});

// Export our Hono app: Hono automatically exports a
// Workers 'fetch' handler for you
export default app;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

8:本地测试代码

npm run start
  • 1.

浏览器打开下面网址

localhost:8787/api/beverages/4
  • 1.

9:远程测试代码

npm run deploy
  • 1.

浏览器打开下面网址

https://d1-tutorial.test.workers.dev/api/beverages/4
  • 1.

10:发布代码

npx wrangler publish
  • 1.