简体   繁体   中英

Java - Using a prepared statement in two methods

I'm kinda starting with connections and all that but i wanted to save a prject to a database I created the connection everything is working fine until i execute the preparedStatement. In the first method it works fine but then (in that same method) I call another method and use the same preparedStatement now with to a different table. But i get a BatchUpdateException. Here is some of the code:

    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;
    }

Your original prepared statement is open when you redirect the variable to a new prepared statement. Your statement.close() isn't closing the obvious instance. This is perhaps poor programming style.

Use a local PreparedStatement variable per method. Don't use a global variable like this. It's just going to get you into trouble.

Try switching to better coding practices and see if your issue disappears.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM