Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This has been adapted from code I already have... there may be an error or two, but the crux will work (it works in my code). Ideally things like this should be done with an ORM tool like Hiberante.</p> <p>Basically you set up the batch update and then run statement.executeBatch() to do the actual update. You are returned with an int[] array with the results. You check these against a list of predefined constants to see what is going on. This is MUCH faster than simply executing each update separately. Furthermore, you can combine all the updates in one transaction, making rollbacks easier.</p> <pre><code>public void updateResNames(List&lt;ResAllocationDTO&gt; list) { String sql = "UPDATE res_allocation SET ResName = ? WHERE PID = ?"; PreparedStatement statement = null; try { statement = connection.prepareStatement(sql); for (ResAllocationDTO dto : list) { statement.setString(1, dto.getResName()); statement.setString(2, dto.getPID()); statement.addBatch(); } int[] result = statement.executeBatch(); for (int i = 0; i &lt; result.length; i++) { if (result[i] == PreparedStatement.EXECUTE_FAILED) { throw new SQLException(String.format("Entry %d failed to execute in the batch insert with a return code of %d.", i, result[i])); } } commit(); } catch (SQLException e) { logger.error(LoggerCodes.DATABASE_ERROR, e); rollback(); throw new RuntimeException(e); } finally { close(statement); } } </code></pre> <p>commit(), close() and rollback() looks like this:</p> <pre><code>public void close(PreparedStatement statement) { try { if (statement != null &amp;&amp; !statement.isClosed()) statement.close(); } catch (SQLException e) { logger.debug(LoggerCodes.TRACE, "Warning! PreparedStatement could not be closed."); } } protected void commit() { try { if ((connection != null) &amp;&amp; !connection.getAutoCommit()) { connection.commit(); } } catch (SQLException e) { logger.debug(LoggerCodes.TRACE, "Warning! ResultSet could not be closed after commit."); } } protected void rollback() { try { if ((connection != null) &amp;&amp; !connection.getAutoCommit()) { connection.rollback(); } } catch (SQLException e) { logger.debug(LoggerCodes.TRACE, "Warning! ResultSet could not be closed after rollback."); } } </code></pre> <p>I hope this helps you! Good luck and happy coding!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload