【发布时间】:2019-11-16 18:08:45
【问题描述】:
我正在尝试将 +/- 250 个单独的插入语句重写为 1 个批处理语句,但它什么也没做。没有错误,没有响应
已遵循本指南: https://www.mkyong.com/jdbc/jdbc-preparedstatement-example-batch-update/
在那之后,许多堆栈溢出,但我看不到问题
我的本地数据库:
<Resource name="jdbc/wtnfV2local" url="jdbc:postgresql://localhost:5432/wtnfV2local"
driverClassName="org.postgresql.Driver" auth="Container" type="javax.sql.DataSource"
username="postgres" password="geheim" />
我不工作的代码:
@Override
public void insertArrayUserV2Voidv2(ArrayList<UserV2> users) {
String insertTableSQL = "INSERT INTO RANK (account, rank, date) VALUES (?,?, to_timestamp(?, 'YYYY-MM-DD\"T\"HH24:MI:SS.ff3\"Z\"'))";
try (Connection conn = baseDao.getConnection();
PreparedStatement preparedStmt = conn.prepareStatement(insertTableSQL);) {
for (UserV2 u : users) {
preparedStmt.setString(1, u.getAccount());
preparedStmt.setString(2, u.getRank());
preparedStmt.setString(3, u.getJoined());
preparedStmt.addBatch();
System.out.println(preparedStmt);
}
System.out.println(conn.getClientInfo());
preparedStmt.executeBatch();
} catch (SQLException e) {
if (e.getErrorCode() == 0) {
} else
throw new WebApplicationException(e.getMessage(), Response.Status.CONFLICT);
}
}
和我之前的工作代码:
@Override
public void insertArrayUserV2Void(ArrayList<UserV2> users) {
String insertTableSQL = "INSERT INTO RANK (account, rank, date) VALUES (?,?, to_timestamp(?, 'YYYY-MM-DD\"T\"HH24:MI:SS.ff3\"Z\"'))";
for (UserV2 u : users) {
try (Connection conn = baseDao.getConnection();
PreparedStatement preparedStmt = conn.prepareStatement(insertTableSQL);) {
preparedStmt.setString(1, u.getAccount());
preparedStmt.setString(2, u.getRank());
preparedStmt.setString(3, u.getJoined());
preparedStmt.execute();
} catch (SQLException e) {
if (e.getErrorCode() == 0) {
} else
throw new WebApplicationException(e.getMessage(), Response.Status.CONFLICT);
}
}
}
预期结果将是 1 次调用中 +/- 250 条插入语句,即使 PK 在其中 1 条上抛出错误,它也会尝试插入所有行。
【问题讨论】:
标签: java postgresql prepared-statement try-with-resources