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
-
You can execute queries on your D1 database through SQL statements.
12
+
1. Prepare your query statement.
13
+
2. If appliable, bind variables into your statement.
14
+
3. Execute your query.
13
15
14
-
###TypeScript support
16
+
## TypeScript support
15
17
16
18
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.
17
19
@@ -37,12 +39,14 @@ const result = await env.MY_DB.prepare(
37
39
38
40
### `db.prepare()`
39
41
40
-
D1 API supports both prepared and static statements.
42
+
Prepares a query statement statement. D1 API supports both prepared and static statements.
41
43
42
44
- 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.
43
45
- 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.
44
46
47
+
:::note
45
48
The recommended approach is to use prepared statements (which are precompiled objects used by the database) to run the SQL. Prepared statements lead to faster overall execution and prevent SQL injection attacks.
49
+
:::
46
50
47
51
Example of a prepared statement with dynamically bound value:
- An array of objects, where each object represents a row of the query result.
30
+
- <code>returnValue</code>: <Typetext="Object"/>
31
+
- An object containing the success status, a meta object, and an array of objects containing the query results.
32
32
- For more information on the returned object, refer to [Return objects](/d1/worker-api/return-object).
33
33
34
34
<Detailsheader="Example of return values"open={false}>
35
35
```js
36
-
conststmt=awaitdb.prepare("SELECT name, age FROM users LIMIT 3");
37
-
const { results } =awaitstmt.run();
38
-
console.log(results);
36
+
constsomeVariable=`Bs Beverages`;
37
+
conststmt=env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
38
+
constreturnValue=awaitstmt.run();
39
+
```
40
+
```js
41
+
returnResponse.json(returnValue);
39
42
```
40
43
```js output
41
-
[
42
-
{
43
-
name:"John",
44
-
age:42,
45
-
},
46
-
{
47
-
name:"Anthony",
48
-
age:37,
44
+
{
45
+
"success":true,
46
+
"meta": {
47
+
"served_by":"miniflare.db",
48
+
"duration":1,
49
+
"changes":0,
50
+
"last_row_id":0,
51
+
"changed_db":false,
52
+
"size_after":8192,
53
+
"rows_read":4,
54
+
"rows_written":0
49
55
},
56
+
"results": [
50
57
{
51
-
name:"Dave",
52
-
age:29,
53
-
},
54
-
]
58
+
"CustomerId":11,
59
+
"CompanyName":"Bs Beverages",
60
+
"ContactName":"Victoria Ashworth"
61
+
},
62
+
{
63
+
"CustomerId":13,
64
+
"CompanyName":"Bs Beverages",
65
+
"ContactName":"Random Name"
66
+
}
67
+
]
68
+
}
55
69
```
56
70
</Details>
57
71
58
72
#### Guidance
59
73
60
74
-`results` is empty for write operations such as UPDATE, DELETE, or INSERT.
61
75
- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `run()` to return a typed result object.
62
-
-`stmt.run()` is functionally equivalent to `stmt.all()` and can be treated as an alias.
63
-
-
76
+
-`stmt.run()` is functionally equivalent to `stmt.all()`, and can be treated as an alias.
77
+
- You can choose to extract only the results you expect from the statement by simply returning the `results` property of the return object.
78
+
79
+
<Detailsheader="Example of returning only the `results`"open={false}>
80
+
```js
81
+
returnResponse.json(returnValue.results);
82
+
```
83
+
```js output
84
+
[
85
+
{
86
+
"CustomerId":11,
87
+
"CompanyName":"Bs Beverages",
88
+
"ContactName":"Victoria Ashworth"
89
+
},
90
+
{
91
+
"CustomerId":13,
92
+
"CompanyName":"Bs Beverages",
93
+
"ContactName":"Random Name"
94
+
}
95
+
]
96
+
```
97
+
</Details>
64
98
65
99
### `stmt.raw()`
66
100
67
-
Returns results as an array of arrays, with each row represented by an array. The return type is an array of arrays, and does not include query metadata.
101
+
Runs the prepared query (or queries), and returns the results as an arrayof arrays. The returned results do not include metadata.
68
102
69
103
Column names are not included in the result set by default. To include column names as the first row of the result array, set `.raw({columnNames: true})`.
[ "name", age ], // The first result array includes the column names
145
+
[
146
+
[
147
+
"CustomerId",
148
+
"CompanyName",
149
+
"ContactName"
150
+
],
151
+
[11, "Bs Beverages",
152
+
"Victoria Ashworth"
153
+
],
154
+
[13, "Bs Beverages",
155
+
"Random Name"
156
+
]
157
+
]
108
158
```
109
159
</Details>
110
160
@@ -114,11 +164,10 @@ console.log(columns);
114
164
115
165
### `stmt.first()`
116
166
117
-
Returns the first row of the query result. This does not return metadata like the other methods. Instead, it directly returns the object.
167
+
Runs the prepared query (or queries), and returns the first row of the query result as an object. This does not return any metadata. Instead, it directly returns the object.
0 commit comments