-
Notifications
You must be signed in to change notification settings - Fork 0
Querying D1
Alex edited this page Oct 4, 2023
·
3 revisions
First, create a D1 client using the builder:
D1 d1 = new D1.builder()
// .withLogLevel(LogLevel.ALL) // Useful for debugging
.withAccountId("...")
.withDatabaseId("...")
.withApiToken("...")
.withApiUrl("https://...") // If for some reason you have access to some private API, omit to use the public Cloudflare API.
.build();Then, using that d1 instance, use query(). Here, we'll retrieve the first result as a JsonObject:
System.out.println(
d1
.query("SELECT * FROM myTable")
.first()
);That prints: {"field":123123}.
You can also use WHERE and pass in parameters:
System.out.println(
d1
.query("SELECT * FROM myOtherTable WHERE id = ?", "someUniqueId")
.first()
);We can also just get the value of field directly:
System.out.println(
d1
.query("SELECT * FROM myTable")
.first("field")
);You can also convert the Json types into your own POJO:
d1
.query("SELECT * FROM myTable")
.first()
.as(MyClass.class);
// Or, if you want an array...
d1
.query("SELECT * FROM myTable")
.all()
.as(MyClass[].class);
// Or, if you want a collection...
d1
.query("SELECT * FROM myTable")
.all()
.as(new TypeToken<List<MyClass>>() {});