Skip to content

Commit

Permalink
Add a convenience method to Connection to prepare and execute a State…
Browse files Browse the repository at this point in the history
…ment only once.

This is useful when initially setting up a database, as the statements won't be used again.

PiperOrigin-RevId: 628480119
Change-Id: I87d746bc754663147fbb36e27a2afdb586c57cc0
  • Loading branch information
tjgq authored and copybara-github committed Apr 26, 2024
1 parent f3af670 commit 7fca56e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,22 @@ public Statement newStatement(String sql) throws IOException {
openStatements.add(stmt);
return stmt;
}

/**
* Executes a statement not expected to return a result.
*
* <p>For statements expected to return a result, or statements that will be executed multiple
* times, use {@link #newStatement}.
*
* @throws IOException if the string contains multiple SQL statements; or the single SQL
* statement could not be parsed and validated; or the statement returned a non-empty
* result; or an execution error occurred
*/
public void executeUpdate(String sql) throws IOException {
try (Statement stmt = new Statement(this, sql)) {
stmt.executeUpdate();
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,18 @@ public void executeUpdate_works() throws Exception {
}
}

@Test
public void executeUpdate_oneShot_works() throws Exception {
try (Connection conn = Sqlite.newConnection(dbPath)) {
conn.executeUpdate("CREATE TABLE tbl (id INTEGER)");

try (Statement stmt = conn.newStatement("SELECT COUNT(*) FROM tbl");
Result result = stmt.executeQuery()) {
assertThat(result.next()).isTrue();
}
}
}

@Test
public void executeUpdate_withParameters_works() throws Exception {
try (Connection conn = Sqlite.newConnection(dbPath)) {
Expand Down

0 comments on commit 7fca56e

Please sign in to comment.