Skip to content

Commit a06345e

Browse files
authored
Update SpannerSample.java
Encapsulates both statements in a try-with-resources statement
1 parent 2ea59f0 commit a06345e

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

samples/snippets/src/main/java/com/example/spanner/SpannerSample.java

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -679,26 +679,27 @@ static void readOnlyTransaction(DatabaseClient dbClient) {
679679
// ReadOnlyTransaction must be closed by calling close() on it to release resources held by it.
680680
// We use a try-with-resource block to automatically do so.
681681
try (ReadOnlyTransaction transaction = dbClient.readOnlyTransaction()) {
682-
ResultSet queryResultSet =
682+
try (ResultSet queryResultSet =
683683
transaction.executeQuery(
684-
Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"));
684+
Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums")) {
685685
while (queryResultSet.next()) {
686686
System.out.printf(
687687
"%d %d %s\n",
688688
queryResultSet.getLong(0), queryResultSet.getLong(1), queryResultSet.getString(2));
689689
}
690-
try (ResultSet readResultSet =
691-
transaction.read(
692-
"Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "AlbumTitle"))) {
693-
while (readResultSet.next()) {
694-
System.out.printf(
695-
"%d %d %s\n",
696-
readResultSet.getLong(0), readResultSet.getLong(1), readResultSet.getString(2));
697-
}
690+
} // queryResultSet.close() is automatically called here
691+
try (ResultSet readResultSet =
692+
transaction.read(
693+
"Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "AlbumTitle"))) {
694+
while (readResultSet.next()) {
695+
System.out.printf(
696+
"%d %d %s\n",
697+
readResultSet.getLong(0), readResultSet.getLong(1), readResultSet.getString(2));
698698
}
699-
}
700-
}
701-
// [END spanner_read_only_transaction]
699+
} // readResultSet.close() is automatically called here
700+
} // transaction.close() is automatically called here
701+
}
702+
// [END spanner_read_only_transaction]
702703

703704
// [START spanner_read_stale_data]
704705
static void readStaleData(DatabaseClient dbClient) {

0 commit comments

Comments
 (0)