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
Copy file name to clipboardExpand all lines: src/content/docs/d1/worker-api/database.mdx
+8-6Lines changed: 8 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -44,20 +44,22 @@ D1 API supports both prepared and static statements.
44
44
45
45
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.
46
46
47
-
Example of a prepared statement:
47
+
Example of a prepared statement with dynamically bound value:
48
48
49
49
```js
50
+
// Dynamically generate the value to use.
51
+
constsomeVariable="John Doe";
50
52
conststmt=db.prepare("SELECT * FROM users WHERE name = ?1").bind(someVariable);
51
53
// A variable (someVariable) will replace the placeholder '?1' in the query.
52
-
//This is a prepared statement.
54
+
//`stmt` is a prepared statement.
53
55
```
54
56
55
57
Example of a static statement:
56
58
57
59
```js
58
60
conststmt=db.prepare('SELECT * FROM users WHERE name = "John Doe"');
59
61
// "John Doe" is hard-coded into the query.
60
-
//This is a static statement.
62
+
//`stmt` will also be a prepared statement.
61
63
```
62
64
63
65
#### Parameters
@@ -74,7 +76,7 @@ const stmt = db.prepare('SELECT * FROM users WHERE name = "John Doe"');
74
76
75
77
- You can pass multiple queries into a single `.prepare()` statement. Simply delineate each query with a semi-colon.
76
78
- The statement only returns the results of the last query, even though all queries are executed.
77
-
- You can only pass parameters to the last query.
79
+
- You can only bind parameters to the last query.
78
80
```js
79
81
conststmt=db.prepare(`SELECT * FROM users WHERE name = "Anthony"; SELECT * FROM users WHERE name = ?1`).bind("Joe")
80
82
```
@@ -137,7 +139,7 @@ await db.batch([
137
139
constrows=awaitdb.batch([
138
140
db.prepare("SELECT * FROM users WHERE name = ?1").bind("John"),
139
141
db.prepare("SELECT * FROM users WHERE name = ?1").bind("Anthony")
0 commit comments