惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
D
Docker
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 司徒正美
博客园 - Franky
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Secure Thoughts
博客园 - 聂微东
L
LINUX DO - 最新话题
U
Unit 42
SecWiki News
SecWiki News
A
Arctic Wolf
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
量子位
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Latest news
Latest news

Flavio Copes

Workers Cache: a cache in front of your Cloudflare Worker Cloudflare Drop: drag a folder, get a live site Temporary Cloudflare accounts: agents can now deploy without signing up Moondream 3.1 on Workers AI: fast vision at the edge inferencecost.dev: what will AI inference cost you at 10k users? Sitebase: all the features your website needs, in one place StackPlan: figure out where to deploy your app, and what it How the Cloudflare Pages build cache works The Summer of Code How I generate an Open Graph image for every post New: 90 free tools for developers How I added search to my static site with Pagefind How to rebuild a Cloudflare site on a schedule Cloudflare Email Workers: run code when an email arrives Cloudflare Turnstile: stop bots without annoying CAPTCHAs Cloudflare Workers: secrets and environments Cloudflare Workers observability: logs and traces Cloudflare Analytics Engine: store and query metrics The AI Workshop (July 2026 cohort) Cloudflare Cron Triggers: run a Worker on a schedule Cloudflare Durable Objects: state that lives in one place Cloudflare Queues: run work in the background Cloudflare R2: object storage without egress fees Cloudflare KV: a key-value store for your Workers Serving a website with Cloudflare Workers static assets Wrangler: the Cloudflare Workers command line tool Executor: one gateway to connect your AI agent to every tool Cloudflare Workers: your first serverless function Vercel eve: an open framework for building AI agents Flue: the open framework for building AI agents Val Town: write and deploy code in seconds A hands-on guide to The Agency, a collection of AI agents The AI Workshop (June 2026 cohort) The AI Workshop (May 2026 cohort) The AI Workshop (Apr 2026 cohort)
Cloudflare D1: a SQL database for your Workers
Flavio Copes · 2026-06-23 · via Flavio Copes

By Flavio Copes

How to create a D1 database, manage its schema with migrations, and query it from a Worker. SQLite, served from the edge.

~~~

Most apps need a real database. On Cloudflare, that’s D1.

D1 is a SQL database built on SQLite. You get tables, indexes, joins, transactions, the whole thing. It lives next to your Workers, so queries are fast, and there’s no connection string to manage or server to keep running.

If you know SQLite, you already know D1. Let’s build with it.

If you’re wondering what D1 costs at your scale, I built a free Workers cost estimator that covers Workers, KV, D1, R2 and Durable Objects.

Create a database

Create one with Wrangler:

npx wrangler d1 create my-app-db

This prints a block of config. Copy it into your wrangler.jsonc so your Worker can find the database:

{
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "my-app-db",
      "database_id": "the-id-it-printed"
    }
  ]
}

The binding is the important part. It’s the name you’ll use in code, here env.DB.

Set up your schema with migrations

You don’t create tables by hand in production. You write migrations: ordered SQL files that describe how your schema changes over time.

Create one:

npx wrangler d1 migrations create my-app-db create_posts

This makes a numbered .sql file in a migrations folder. Open it and write the SQL:

create table posts (
  id integer primary key autoincrement,
  title text not null,
  body text,
  created_at integer not null
);

Apply it to your local database while developing:

npx wrangler d1 migrations apply my-app-db --local

And to the real one when you deploy:

npx wrangler d1 migrations apply my-app-db --remote

Migrations run in order, and each runs once. So your local and production databases stay in sync.

Query from a Worker

Now the fun part. You query D1 through the env.DB binding.

To read rows, use prepare, then all():

export default {
  async fetch(request, env) {
    const { results } = await env.DB.prepare(
      'select * from posts order by created_at desc'
    ).all()

    return Response.json(results)
  },
}

results is a plain array of objects, one per row.

Use parameters, always

When a value comes from the user, never glue it into the SQL string. Use ? placeholders and bind:

const { results } = await env.DB.prepare(
  'select * from posts where id = ?'
).bind(postId).all()

This is how you avoid SQL injection. D1 handles the escaping for you.

Insert and update

For writes, use run():

await env.DB.prepare(
  'insert into posts (title, body, created_at) values (?, ?, ?)'
).bind('Hello', 'My first post', Date.now()).run()

When you only expect one row back, first() is handy:

const post = await env.DB.prepare(
  'select * from posts where id = ?'
).bind(postId).first()

first() returns the single object, or null if nothing matched.

Many statements at once

If you need to run several writes together, batch sends them in one round trip:

await env.DB.batch([
  env.DB.prepare('update accounts set balance = balance - ? where id = ?').bind(10, 'alice'),
  env.DB.prepare('update accounts set balance = balance + ? where id = ?').bind(10, 'bob'),
])

When D1 is the right call

D1 is great for the structured data at the heart of an app: users, posts, orders, settings. Anything you’d reach for SQL to query.

It’s not meant for huge blobs of files (that’s R2) or simple key lookups where you don’t need queries (that’s KV). I’ll cover both of those next.

For everything relational, D1 is my default. The full reference is in the D1 docs.

~~~

Related posts about cloudflare: