D1 Get started
Query D1 from Hono
$ npx wrangler d1 create prod-d1-tutorial
⛅️ wrangler 3.103.2
--------------------
✅ Successfully created DB 'prod-d1-tutorial' in region WNAM
Created your new D1 database.
[[d1_databases]]
binding = "DB"
database_name = "prod-d1-tutorial"
database_id = "<uuid>"
$ vi wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "prod-d1-tutorial"
database_id = "<uuid>"
$ vi 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');
$ npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql
$ npx wrangler d1 execute prod-d1-tutorial --local --command="SELECT * FROM Customers"
┌────────────┬─────────────────────┬───────────────────┐
│ CustomerId │ CompanyName │ ContactName │
├────────────┼─────────────────────┼───────────────────┤
│ 1 │ Alfreds Futterkiste │ Maria Anders │
├────────────┼─────────────────────┼───────────────────┤
│ 4 │ Around the Horn │ Thomas Hardy │
├────────────┼─────────────────────┼───────────────────┤
│ 11 │ Bs Beverages │ Victoria Ashworth │
├────────────┼─────────────────────┼───────────────────┤
│ 13 │ Bs Beverages │ Random Name │
└────────────┴─────────────────────┴───────────────────┘
$ vi src/index.tsx
import { Hono } from 'hono'
import { renderer } from './renderer'
type Bindings = {
DB: D1Database;
};
const app = new Hono<{ Bindings: Bindings }>();
app.use(renderer)
app.get('/', async (c) => {
//return c.render(<h1>Hello!</h1>)
const { results } = await c.env.DB.prepare(
"SELECT * FROM Customers WHERE CompanyName = ?",
)
.bind("Bs Beverages")
.all();
return c.json(results);
})
export default app
$ npm run dev
$ curl -s http://localhost:5173/ | jq .
[
{
"CustomerId": 11,
"CompanyName": "Bs Beverages",
"ContactName": "Victoria Ashworth"
},
{
"CustomerId": 13,
"CompanyName": "Bs Beverages",
"ContactName": "Random Name"
}
]
- wrangler.tomlを.gitignoreに追加
- githubにmainブランチでアップロード
- 以下のビルド設定でCloudflare Pagesへデブロイ
- Workers & Pages / レポジトリ名 > 設定 > バインディング追加 > D1データベース
- 変数名DB、D1データベースをprod-d1-tutorialで指定して保存、再度デブロイ