Getting started (6)·续

After you have set up your database, run an SQL query from within your Worker.

  1. Navigate to your d1-tutorial Worker and open the index.ts file. The index.ts file is where you configure your Worker's interactions with D1.
  2. Clear the content of index.ts.
  3. Paste the following code snippet into your index.ts file:

index.jsjs

   export default {
    async fetch(request, env) {
        const { pathname } = new URL(request.url);

if (pathname === "/api/beverages") {
            // If you did not use `DB` as your binding name, change it here
            const { results } = await env.prod_d1_tutorial
                .prepare("SELECT * FROM Customers WHERE CompanyName = ?")
                .bind("Bs Beverages")
                .run();
            return Response.json(results);
        }

return new Response(
            "Call /api/beverages to see everyone who works at Bs Beverages",
        );
    },
   };
   ```

*index.tsts*

```ts
   export interface Env {
    // If you set another name in the Wrangler config file for the value for 'binding',
    // replace "DB" with the variable name you defined.
    prod_d1_tutorial: D1Database;
   }

export default {
    async fetch(request, env): Promise<Response> {
        const { pathname } = new URL(request.url);

if (pathname === "/api/beverages") {
            // If you did not use `DB` as your binding name, change it here
            const { results } = await env.prod_d1_tutorial.prepare(
                "SELECT * FROM Customers WHERE CompanyName = ?",
            )
                .bind("Bs Beverages")
                .run();
            return Response.json(results);
        }

return new Response(
            "Call /api/beverages to see everyone who works at Bs Beverages",
        );
    },
   } satisfies ExportedHandler<Env>;
   ```

*entry.pypython*

```python
   from workers import Response, WorkerEntrypoint
   from urllib.parse import urlparse

class Default(WorkerEntrypoint):
       async def fetch(self, request):
           pathname = urlparse(request.url).path
           if pathname == "/api/beverages":
               query = (
                   await self.env.prod_d1_tutorial.prepare(
                       "SELECT * FROM Customers WHERE CompanyName = ?",
                   )
                   .bind("Bs Beverages")
                   .run()
               )
               return Response.json(query.results)
           return Response(
               "Call /api/beverages to see everyone who works at Bs Beverages"
           )
   ```

In the code above, you:
   1. Define a binding to your D1 database in your code. This binding matches the `binding` value you set in the [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/) under `d1_databases`.
   2. Query your database using `env.prod_d1_tutorial.prepare` to issue a [prepared query](https://developers.cloudflare.com/d1/worker-api/d1-database/#prepare) with a placeholder (the `?` in the query).
   3. Call `bind()` to safely and securely bind a value to that placeholder. In a real application, you would allow a user to pass the `CompanyName` they want to list results for. Using `bind()` prevents users from executing arbitrary SQL (known as "SQL injection") against your application and deleting or otherwise modifying your database.
   4. Execute the query by calling [`run()`](https://developers.cloudflare.com/d1/worker-api/prepared-statements/#run) to return all rows (or none, if the query returns none).
   5. Return your query results, if any, in JSON format with `Response.json(results)`.

After configuring your Worker, you can test your project locally before you deploy globally.

You can query your D1 database using your Worker.

1. In the Cloudflare dashboard, go to the **Workers & Pages** page. [Go to **Workers & Pages** ↗](https://dash.cloudflare.com/?to=/:account/workers-and-pages)
2. Select the `d1-tutorial` Worker you created.
3. Select the **Edit code** icon (**\&lt;/>**).
4. Clear the contents of the `worker.js` file, then paste the following code:

```js
   export default {
    async fetch(request, env) {
        const { pathname } = new URL(request.url);

if (pathname === "/api/beverages") {
            // If you did not use `DB` as your binding name, change it here
            const { results } = await env.prod_d1_tutorial.prepare(
                "SELECT * FROM Customers WHERE CompanyName = ?"
            )
                .bind("Bs Beverages")
                .run();
            return new Response(JSON.stringify(results), {
                headers: { 'Content-Type': 'application/json' }
            });
        }

return new Response(
            "Call /api/beverages to see everyone who works at Bs Beverages"
        );
    },
   };
   ```

5. Select **Save**.

## 5. Deploy your application

Deploy your application on Cloudflare's global network.

To deploy your Worker to production using Wrangler, you must first repeat the [database configuration](https://developers.cloudflare.com/d1/get-started/#populate-your-d1-database) steps after replacing the `--local` flag with the `--remote` flag to give your Worker data to read. This creates the database tables and imports the data into the production version of your database.

1. Create tables and add entries to your remote database with the `schema.sql` file you created in step 4. Enter `y` to confirm your decision.

```sh
   npx wrangler d1 execute prod-d1-tutorial --remote --file=./schema.sql
   ```

```txt
   🌀 Executing on remote database prod-d1-tutorial (<DATABASE_ID>):
   🌀 To execute on your local development database, remove the --remote flag from your wrangler command.
   Note: if the execution fails to complete, your DB will return to its original state and you can safely retry.
   ├ 🌀 Uploading <DATABASE_ID>.a7f10c4651cc3a26.sql
   │ 🌀 Uploading complete.
   │
   🌀 Starting import...
   🌀 Processed 3 queries.
   🚣 Executed 3 queries in 0.00 seconds (5 rows read, 6 rows written)
   Database is currently at bookmark 00000000-0000000a-00004f6d-b85c16a3dbcf077cb8f258b4d4eb965e.
   ┌────────────────────────┬───────────┬──────────────┬────────────────────┐
   │ Total queries executed │ Rows read │ Rows written │ Database size (MB) │
   ├────────────────────────┼───────────┼──────────────┼────────────────────┤
   │ 3                      │ 5         │ 6            │ 0.02               │
   └────────────────────────┴───────────┴──────────────┴────────────────────┘
   ```

2. Validate the data is in production by running:

```sh
   npx wrangler d1 execute prod-d1-tutorial --remote --command="SELECT * FROM Customers"
   ```

```txt
   ⛅️ wrangler 4.33.1
   ───────────────────
   🌀 Executing on remote database jun-d1-db-gs-2025 (cf91ec5c-fa77-4d49-ad8e-e22921b996b2):
   🌀 To execute on your local development database, remove the --remote flag from your wrangler command.
   🚣 Executed 1 command in 0.1797ms
   ┌────────────┬─────────────────────┬───────────────────┐
   │ CustomerId │ CompanyName         │ ContactName       │
   ├────────────┼─────────────────────┼───────────────────┤
   │ 1          │ Alfreds Futterkiste │ Maria Anders      │
   ├────────────┼─────────────────────┼───────────────────┤
   │ 4          │ Around the Horn     │ Thomas Hardy      │
   ├────────────┼─────────────────────┼───────────────────┤
   │ 11         │ Bs Beverages        │ Victoria Ashworth │
   ├────────────┼─────────────────────┼───────────────────┤
   │ 13         │ Bs Beverages        │ Random Name       │
   └────────────┴─────────────────────┴───────────────────┘
   ```

3. Deploy your Worker to make your project accessible on the Internet. Run:

```sh
   npx wrangler deploy
   ```

```txt
   ⛅️ wrangler 4.33.1
   ────────────────────
   Total Upload: 0.52 KiB / gzip: 0.33 KiB
   Your Worker has access to the following bindings:
   Binding                                        Resource
   env.prod_d1_tutorial (prod-d1-tutorial)        D1 Database

Uploaded prod-d1-tutorial (4.17 sec)
   Deployed prod-d1-tutorial triggers (3.49 sec)
   https://prod-d1-tutorial.pcx-team.workers.dev
   Current Version ID: 42c82f1c-ff2b-4dce-9ea2-265adcccd0d5
   ```

You can now visit the URL for your newly created project to query your live database.

For example, if the URL of your new Worker is `d1-tutorial.<YOUR_SUBDOMAIN>.workers.dev`, accessing `https://d1-tutorial.<YOUR_SUBDOMAIN>.workers.dev/api/beverages` sends a request to your Worker that queries your live database directly.
4. Test your database is running successfully. Add `/api/beverages` to the provided Wrangler URL. For example, `https://d1-tutorial.<YOUR_SUBDOMAIN>.workers.dev/api/beverages`.

1. In the Cloudflare dashboard, go to the **Workers & Pages** page. [Go to **Workers & Pages** ↗](https://dash.cloudflare.com/?to=/:account/workers-and-pages)
2. Select your `d1-tutorial` Worker.
3. Select **Deployments**.
4. From the **Version History** table, select **Deploy version**.
5. From the **Deploy version** page, select **Deploy**.

This deploys the latest version of the Worker code to production.

## 6. (Optional) Develop locally with Wrangler

If you are using D1 with Wrangler, you can test your database locally. While in your project directory:

1. Run `wrangler dev`:

```sh
   npx wrangler dev
   ```

When you run `wrangler dev`, Wrangler provides a URL (most likely `localhost:8787`) to review your Worker.
2. Go to the URL.

The page displays `Call /api/beverages to see everyone who works at Bs Beverages`.
3. Test your database is running successfully. Add `/api/beverages` to the provided Wrangler URL. For example, `localhost:8787/api/beverages`.

If successful, the browser displays your data.

Note

You can only develop locally if you are using Wrangler. You cannot develop locally through the Cloudflare dashboard.

## 7. (Optional) Delete your database

To delete your database:

Run:

```sh
npx wrangler d1 delete prod-d1-tutorial
  1. In the Cloudflare dashboard, go to the D1 SQL database page. Go to D1 SQL database ↗
  2. Select your prod-d1-tutorial D1 database.
  3. Select Settings.
  4. Select Delete.
  5. Type the name of the database ( prod-d1-tutorial) to confirm the deletion.

Caution

Note that deleting your D1 database will stop your application from functioning as before.

If you want to delete your Worker:

Run:

npx wrangler delete d1-tutorial
  1. In the Cloudflare dashboard, go to the Workers & Pages page. Go to Workers & Pages ↗
  2. Select your d1-tutorial Worker.
  3. Select Settings.
  4. Scroll to the bottom of the page, then select Delete.
  5. Type the name of the Worker ( d1-tutorial) to confirm the deletion.

Summary

In this tutorial, you have:

  • Created a D1 database
  • Created a Worker to access that database
  • Deployed your project globally

Next steps

If you have any feature requests or notice any bugs, share your feedback directly with the Cloudflare team by joining the Cloudflare Developers community on Discord ↗︎.

Was this helpful?

YesNo

On this page

Getting started (6)·续 - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/d1/get-started/#page","headline":"Getting started","description":"Create your first D1 database, define a schema, and query it from a Cloudflare Worker.","url":"https://developers.cloudflare.com/d1/get-started/","inLanguage":"en","image":"https://developers.cloudflare.com/d1/get-started/og.png?v=f4bd290d0b828d3b","dateModified":"2026-08-25","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}


description: Import existing SQLite tables into D1 or export a D1 database for local use. title: Import and export data image: https://developers.cloudflare.com/d1/best-practices/import-export-data/og.png?v=bbc73732a0afdd37


Skip to content

Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/d1/llms.txt
Use this file to discover all available pages before exploring further.