diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index b7ca77a05..d7824886d 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -218,13 +218,11 @@ jobject _duckdb_jdbc_prepare(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArr throw InvalidInputException("No statements to execute."); } - // if there are multiple statements, we directly execute the statements besides the last one - // we only return the result of the last statement to the user, unless one of the previous statements fails - for (idx_t i = 0; i + 1 < statements.size(); i++) { - auto res = conn_ref->Query(std::move(statements[i])); - if (res->HasError()) { - res->ThrowError(); - } + // preparing must not have side effects, so multiple statements are rejected instead of + // executing all statements besides the last one + if (statements.size() > 1) { + throw InvalidInputException("Cannot prepare multiple statements at once, statements count: " + + std::to_string(statements.size())); } auto stmt_ref = make_uniq(); diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index d418d0a38..5b1e99e14 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -498,6 +498,22 @@ public static void test_multiple_statements_exception() throws Exception { } } + public static void test_multiple_statements_prepare_rejected() throws Exception { + try (Connection conn = DriverManager.getConnection(JDBC_URL)) { + assertThrows(() -> { conn.prepareStatement("CREATE TABLE z(i int); SELECT 1 AS x"); }, SQLException.class); + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT count(*) FROM duckdb_tables() WHERE table_name = 'z'")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 0); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("CREATE TABLE z(i int); SELECT 1 AS x")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 1); + } + } + } + public static void test_crash_bug496() throws Exception { Connection conn = DriverManager.getConnection(JDBC_URL); Statement stmt = conn.createStatement();