[英]Java - Using a prepared statement in two methods
我有点从连接之类的东西开始,但我想将一个对象保存到数据库中,我创建了连接,一切正常,直到执行了preparedStatement。 在第一种方法中,它可以正常工作,但随后(在同一方法中)我调用了另一种方法,并且现在将相同的prepareStatement用于不同的表。 但是我得到一个BatchUpdateException。 这是一些代码:
public void openConnection() throws SQLException {
DriverManager.registerDriver
(new oracle.jdbc.OracleDriver());
connection = DriverManager.getConnection(jdbcUrl, username, password);
connection.setAutoCommit(false);
}
public boolean addProject(Project proj)
throws SQLException {
stmt = connection.prepareStatement("insert into PROJECT (p_name, description) values (?, ?)");
stmt.setString(1, proj.getName());
stmt.setString(2, proj.getDescription());
stmt.addBatch();
try {
stmt.executeBatch();
} catch (BatchUpdateException e) {
System.out.println("plop");
return false;
}
boolean flag1 = addSimulationList(proj);
boolean flag2 = addRoadNetwork(proj);
boolean flag3 = addVehicleList(proj);
if (flag1 == false || flag2 == false || flag3 == false) {
return false;
}
connection.commit();
stmt.close();
return true;
}
/**
* Adds a specific simulation to the table "Simulations".
*
* @param proj Project
*/
public boolean addSimulationList(Project proj)
throws SQLException {
stmt = connection.prepareStatement("insert into SIMULATION (p_name, s_code, description) values (?, ?, ?)");
boolean flag1 = true, flag2 = true;
for (Simulation s : proj.getSimList()) {
stmt.setString(1, proj.getName());
stmt.setString(2, s.getSimID());
stmt.setString(3, s.getDescription());
stmt.addBatch();
}
int[] totalInserted = new int[proj.getSimList().size()];
try {
totalInserted = stmt.executeBatch(); //it triggers here
} catch (BatchUpdateException e) {
totalInserted = e.getUpdateCounts();
return false;
}
当您将变量重定向到新的预处理语句时,原始的预处理语句将打开。 您的statement.close()没有关闭明显的实例。 这可能是不良的编程风格。
每个方法使用局部的PreparedStatement变量。 不要使用这样的全局变量。 这只会使您陷入困境。
尝试改用更好的编码方法,看看问题是否消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.