I need to take a table from one database and upload it to a different database. So, I create two separate connection . Here is my code
Connection connection1 = // set up connection to dbms1
Statement statement = connection1.createStatement();
ResultSet result = statement.executeQuery("select * from ............. ");
Connection connection2 = // set up connection to dbms2
// Now I want to upload the ResultSet result into the second database
Statement statement2 = connection2.createStatement("insert into table2 " + result);
statement2.executeUpdate();
The above last lines do not work How can i do this ? The bottomline is how to reuse a ready resultset
ResultSet is a ready java object . I hope there is a way add it to batch or something like this and executeUpdate
, but not to write the result set to some temporary space (List
, csv
etc.) and the insert
If you don't want to manually list out all the field names for every table in the database, you should be able to do this two-step process instead:
resultSet.getMetaData()
to get the list of fields, and use that to drive a modified version of the SELECT/INSERT code in @Wyzard's answer.I will post code here if I get it working.
The simplest way to do this is with a prepared statement for the insert. It lets you create a single statement object that can be used to run the query multiple times with different parameter values.
The rows are inserted into
table2
as you iterate through the results fromtable1
, so there's no need to store the whole result set.You can also use the prepared statement's
addBatch()
andexecuteBatch()
methods to queue up all the inserts and send them to the database all at once, instead of sending a separate message to the database for each individual inserted row. But that forces JDBC to hold all the pending inserts in memory locally, which it seems you're trying to avoid. So the one-row-at-a-time inserts are your best bet in this case.