java – How to create two different database connections?


I need to pass data from one database (DB2) to the other (MySQL), and I'm thinking about how to do this, as in the database I have the data I don't have access to some tools, such as backup , I can only SELECT , I I thought about making two connections with JDBC , getting the records and already inserting them in MySQL, how? Or is it better for me to save it to a txt and then switch to MySQL?


You can open two connections to different databases and then insert data read from one database into the other something like this:

String urlMySql = "jdbc:mysql://localhost:3306/seu_database_mysql";
String urlDb2 = "jdbc:db2://localhost:50000/seu_database_db2";

Connection connMySql = DriverManager.getConnection(urlMySql);
Connection connDb2 = DriverManager.getConnection(urlDb2);

PreparedStatement selectDb2 = connDb2.prepareStatement("SELECT * FROM TABELA");
ResultSet rsDb2 = selectDb2.executeQuery();

while ( {
    PreparedStatement insertMySql = connMySql.prepareStatement("INSERT INTO OUTRA_TABELA VALUES...");

From there, all you have to do is manage the Connection s, PreparedStatement and ResultSet s as usual (including closing them in a finally block or using try-with-resources ).

It is also valid to encapsulate Connection s in DAOs, pool connections, or separate any database operation into multiple classes and/or multiple methods. Just keep in mind that there can be more than one database connection active at the same time (along with their PreparedStatement and ResultSet s).

Scroll to Top