D1 Database
To interact with your D1 database from your Worker, you need to access it through the environment bindings provided to the Worker (env
).
A D1 binding has the type D1Database
, and supports a number of methods, as listed below.
Prepares a query statement to be later executed.
query
: String Required- The SQL query you wish to execute on the database.
D1PreparedStatement
: Object- An object which only contains methods. Refer to Prepared statement methods.
You can use the bind
method to dynamically bind a value into the query statement, as shown below.
-
Example of a static statement without using
bind
: -
Example of an ordered statement using
bind
:
Refer to the bind
method documentation for more information.
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.
Batched statements are SQL transactions ↗. 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.
To send batch statements, provide D1Database::batch
a list of prepared statements and get the results in the same order.
statements
: Array- An array of
D1PreparedStatement
s.
- An array of
results
: Array- An array of
D1Result
objects containing the results of theD1Database::prepare
statements. Each object is in the array position corresponding to the array position of the initialD1Database::prepare
statement within thestatements
. - Refer to
D1Result
for more information about this object.
- An array of
Example of return values
-
You can construct batches reusing the same prepared statement:
Executes one or more queries directly without prepared statements or parameter bindings.
query
: String Required- The SQL query statement without parameter binding.
D1ExecResult
: Object- The
count
property contains the number of executed queries. - The
duration
property contains the duration of operation in milliseconds.- Refer to
D1ExecResult
for more information.
- Refer to
- The
Example of return values
- If an error occurs, an exception is thrown with the query and error messages, execution stops and further statements are not executed. Refer to Errors to learn more.
- This method can have poorer performance (prepared statements can be reused in some cases) and, more importantly, is less safe.
- Only use this method for maintenance and one-shot tasks (for example, migration jobs).
- The input can be one or multiple queries separated by
\n
.
Dumps the entire D1 database to an SQLite compatible file inside an ArrayBuffer.
- None.
- None.