How to create two connections with different databases?

3

I need to pass data from one database (DB2) to another (MySQL), and I'm thinking about how to do this, as in the database I have the data I do not have access to some tools, / em>, I can only do SELECT , I thought of making two connections with JDBC , get the records and already insert them in MySQL, how? Or should I save in a txt and then move to MySQL?

    
asked by anonymous 24.01.2015 / 16:17

2 answers

1

You can open two connections to different databases and then insert the data read from one database into the other more or less 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 (rsDb2.next()) {
    PreparedStatement insertMySql = connMySql.prepareStatement("INSERT INTO OUTRA_TABELA VALUES...");
    insertMySql.setXXX(rsDb2.getXXX(...));
    insertMySql.executeUpdate();
}
So, 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% s of% s in DAOs, put connections into pools, or separate any database operation into multiple classes and / or various methods. Just keep in mind that there may be more than one connection to the active database at the same time (along with their Connection s and PreparedStatement s).

    
24.01.2015 / 17:16
1

You can not have a single con referencing two database connections. You definitely need to keep two different references.

Connection con1 = DriverManger.getConnection( connect1 );  
Connection con2 = DriverManger.getConnection( connect2 );  

There is no other alternative.

Solution 1: Create multiple methods to return local and remote connection.

public Connection getLocalConnection() {
  ...
  Connection localCon = DriverManger.getConnection( connect1 );  
  ...
  return localCon;
}

public Connection getRemoteConnection() {
  ...
  Connection remoteCon = DriverManger.getConnection( connect2 );  
  ...
  return remoteCon;
}

Solution 2: If you want to generate so much connection on each call and return them, you'd better use an object from the list to go back:

public List<Connection> createConnection() {
  ...
  Connection localCon = DriverManger.getConnection( connect1 );  
  Connection remoteCon = DriverManger.getConnection( connect2 );  
  ...
  List<Connection> connectionsList = new ArrayList<Connection>( 2 );
  connectionsList.add( localCon );
  connectionsList.add( remoteCon );
  ...
  return connectionsList;
}

I'd rather use Solution 1, because sometimes you might be checking some data in a single database.

    
24.01.2015 / 17:30