You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You can execute queries on your D1 database through SQL query statements. To do this, you need to follow these steps:
11
11
12
-
1. Prepare your query statement.
13
-
2. If appliable, bind variables into your statement.
14
-
3. Execute your query.
12
+
1. Prepare your query statement (including binding variables into the statement).
13
+
2. Execute your query.
14
+
15
+
This chapter documents how to prepare a statement and how to execute them.
15
16
16
17
## TypeScript support
17
18
18
19
D1 Worker Bindings API is fully-typed via the `@cloudflare/workers-types` package, and also supports [generic types](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types) as part of its TypeScript API. A generic type allows you to provide an optional _type parameter_ so that a function understands the type of the data it is handling.
19
20
20
-
When using the [query statement methods](#query-statement-methods)`stmt.all()`, `stmt.raw()` and `stmt.first()`, you can provide a type representing each database row. D1's API will [return the result object](#return-object) with the correct type.
21
+
When using the [query statement methods](#query-statement-methods)`stmt.run()`, `stmt.raw()` and `stmt.first()`, you can provide a type representing each database row. D1's API will [return the result object](#return-object) with the correct type.
21
22
22
-
For example, providing an `OrderRow` type as a type parameter to `stmt.all()` will return a typed `Array<OrderRow>` object instead of the default `Record<string, unknown>` type:
23
+
For example, providing an `OrderRow` type as a type parameter to `stmt.run()` will return a typed `Array<OrderRow>` object instead of the default `Record<string, unknown>` type:
23
24
24
25
```ts
25
26
// Row definition
@@ -32,14 +33,16 @@ type OrderRow = {
32
33
// Elsewhere in your application
33
34
const result =awaitenv.MY_DB.prepare(
34
35
"SELECT Id, CustomerName, OrderDate FROM [Order] ORDER BY ShippedDate DESC LIMIT 100",
35
-
).all<OrderRow>();
36
+
).run<OrderRow>();
36
37
```
37
38
38
39
## Methods
39
40
40
41
### `db.prepare()`
41
42
42
-
Prepares a query statement statement. D1 API supports both prepared and static statements.
43
+
Prepares a query statement to be later executed.
44
+
45
+
D1 API supports both prepared and static statements.
43
46
44
47
- Prepared statements are SQL statements where the variables are dynamically determined. When writing a prepared statement, you insert variables into placeholders within the statement string.
45
48
- Static statements are SQL statements where the variables have been hard coded. When writing a static statement, you manually type the variable within the statement string.
@@ -51,19 +54,18 @@ The recommended approach is to use prepared statements (which are precompiled ob
51
54
Example of a prepared statement with dynamically bound value:
52
55
53
56
```js
54
-
// Dynamically generate the value to use.
55
-
constsomeVariable="John Doe";
56
-
conststmt=db.prepare("SELECT * FROM users WHERE name = ?1").bind(someVariable);
57
-
// A variable (someVariable) will replace the placeholder '?1' in the query.
57
+
constsomeVariable=`Bs Beverages`;
58
+
conststmt=env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
59
+
// A variable (someVariable) will replace the placeholder '?' in the query.
58
60
// `stmt` is a prepared statement.
59
61
```
60
62
61
63
Example of a static statement:
62
64
63
65
```js
64
-
conststmt=db.prepare('SELECT * FROM users WHERE name = "John Doe"');
65
-
// "John Doe" is hard-coded into the query.
66
-
// `stmt` will also be a prepared statement.
66
+
conststmt=env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = Bs Beverages");
67
+
// "Bs Beverages" is hard-coded into the query.
68
+
// `stmt` is a static statement.
67
69
```
68
70
69
71
#### Parameters
@@ -73,8 +75,7 @@ const stmt = db.prepare('SELECT * FROM users WHERE name = "John Doe"');
73
75
74
76
#### Return values
75
77
76
-
- <code>queryResult</code>:
77
-
- The result of the SQL query.
78
+
- None.
78
79
79
80
#### Guidance
80
81
@@ -96,33 +97,36 @@ const stmt = db.prepare('SELECT * FROM users WHERE name = "John Doe"');
96
97
Order and anonymous examples:
97
98
98
99
```js
99
-
conststmt=db.prepare("SELECT * FROM users WHERE name = ?").bind("John Doe");
100
+
conststmt=db.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind("");
100
101
```
101
102
102
103
```js
103
104
conststmt= db
104
-
.prepare("SELECT * FROM users WHERE name = ? AND age = ?")
105
-
.bind("John Doe", 41);
105
+
.prepare("SELECT * FROM Customers WHERE CompanyName = ? AND CustomerId = ?")
106
+
.bind("Alfreds Futterkiste", 1);
106
107
```
107
108
108
109
```js
109
110
conststmt= db
110
-
.prepare("SELECT * FROM users WHERE name = ?2 AND age = ?1")
111
-
.bind(41, "John Doe");
111
+
.prepare("SELECT * FROM Customers WHERE CompanyName = ?2 AND CustomerId = ?1")
112
+
.bind(1, "Alfreds Futterkiste");
112
113
```
113
114
114
115
### `db.batch()`
115
116
116
-
Batching sends multiple SQL statements inside a single call to the database. This can have a huge performance impact as it reduces latency from network round trips to D1. D1 operates in auto-commit. Our implementation guarantees that each statement in the list will execute and commit, sequentially, non-concurrently.
117
+
Sends multiple SQL statements inside a single call to the database. This can have a huge performance impact as it reduces latency from network round trips to D1. D1 operates in auto-commit. Our implementation guarantees that each statement in the list will execute and commit, sequentially, non-concurrently.
117
118
118
119
Batched statements are [SQL transactions](https://www.sqlite.org/lang_transaction.html). If a statement in the sequence fails, then an error is returned for that specific statement, and it aborts or rolls back the entire sequence.
119
120
120
121
To send batch statements, provide `.batch()` a list of prepared statements and get the results in the same order.
121
122
122
123
```js
123
-
awaitdb.batch([
124
-
db.prepare("UPDATE users SET name = ?1 WHERE id = ?2").bind("John", 17),
125
-
db.prepare("UPDATE users SET age = ?1 WHERE id = ?2").bind(35, 19),
124
+
constcompanyName1=`Bs Beverages`;
125
+
constcompanyName2=`Around the Horn`;
126
+
conststmt=env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`);
127
+
constbatchResult=awaitenv.DB.batch([
128
+
stmt.bind(companyName1),
129
+
stmt.bind(companyName2)
126
130
]);
127
131
```
128
132
@@ -140,35 +144,73 @@ await db.batch([
140
144
<Detailsheader="Example of return values"open={false}>
141
145
142
146
```js
143
-
constrows=awaitdb.batch([
144
-
db.prepare("SELECT * FROM users WHERE name = ?1").bind("John"),
145
-
db.prepare("SELECT * FROM users WHERE name = ?1").bind("Anthony")
147
+
constcompanyName1=`Bs Beverages`;
148
+
constcompanyName2=`Around the Horn`;
149
+
conststmt=awaitenv.DB.batch([
150
+
env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`).bind(companyName1),
151
+
env.DB.prepare(`SELECT * FROM Customers WHERE CompanyName = ?`).bind(companyName2)
0 commit comments