The easiest way to do this is to create a prepared report for insertion. It allows you to create one operator object that can be used to run a query multiple times with different parameter values.
try (final Statement statement1 = connection1.createStatement(), final PreparedStatement insertStatement = connection2.prepareStatement("insert into table2 values(?, ?)")) { try (final ResultSet resultSet = statement1.executeQuery("select foo, bar from table1")) { while (resultSet.next()) {
Rows are inserted into table2 when repeating the results from table1 , so there is no need to store the entire result set.
You can also use prepared addBatch() and executeBatch() instructions to queue all insertions and send them to the database at the same time, instead of sending a separate message to the database for each individual row inserted. But this forces JDBC to hold all pending inserts in memory locally, which seems to be an attempt to avoid. Thus, in this case, you can bet on one line at a time.
Wyzard
source share