gpt4 book ai didi

java需要h2数据库抛出jdbc异常

转载 作者:行者123 更新时间:2023-11-30 06:39:14 31 4
gpt4 key购买 nike

我正在为一些与数据库交互的代码编写测试。我的代码有一个 try-catch 来查找 BatchUpdateException。但是,在我的测试类中,我使用内存数据库 (H2),当插入失败时,它不会抛出 BatchUpdateException。它抛出一个org.h2.jdbc.JdbcSQLException

我希望能够用测试用例来覆盖 Catch 子句。我怎样才能做到这一点?

最佳答案

你不能让你的测试代码捕获org.h2.jdbc.JdbcSQLException然后抛出一个新的java.sql.BatchUpdateException吗?这似乎对我有用......

package h2demo;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class H2DemoMain {

public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:test")) {
try (Statement st = conn.createStatement()) {
// set up test environment
st.execute("CREATE TABLE table1 (id INT PRIMARY KEY)");
st.execute("INSERT INTO table1 (id) VALUES (2)");
}
try {
doBatchUpdate(conn);
} catch (BatchUpdateException bue) {
System.out.println("BatchUpdateException caught: " + bue.getMessage());
System.out.println();
System.out.println("Update counts returned by exception:");
for (int i : bue.getUpdateCounts()) {
System.out.println(i);
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}

}

private static int[] doBatchUpdate(Connection conn) throws SQLException {
int[] updateCounts = null;
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO table1 (id) VALUES (?)")) {
ps.setInt(1, 1);
ps.addBatch();
ps.setInt(1, 2);
ps.addBatch();
ps.setInt(1, 3);
ps.addBatch();
updateCounts = ps.executeBatch();
} catch (org.h2.jdbc.JdbcSQLException jse) {
throw new BatchUpdateException(jse.getMessage(), updateCounts, jse);
}
return updateCounts;
}

}

...生成以下控制台 (System.out) 输出:

BatchUpdateException caught: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.TABLE1(ID)"; SQL statement:
INSERT INTO table1 (id) VALUES (?) [23505-196]

Update counts returned by exception:
1
-3
1

关于java需要h2数据库抛出jdbc异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685323/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com