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

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

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: