java同时连接db2和mysql的程序
db2的jar包安装参见:http://www.cnblogs.com/zifeiy/p/7918554.html
代码:
package com.anbank.datafetch;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.ibm.db2.jcc.DB2Driver;
public class DataFetch {
private static String APPENDED_DB_INFO
= "?useUnicode=true&characterEncoding=UTF8"
+ "&rewriteBatchedStatements=true"
+ "&useLegacyDatetimeCode=false"
+ "&serverTimezone=Asia/Shanghai"
+ "&useSSL=false";
// DB2
private String db2ClassName = "com.ibm.db2.jcc.DB2Driver";
private String db2Url = "jdbc:db2://localhost:50000/zi";
private String db2User = "db2admin";
private String db2Password = "password";
Connection db2Connection = null;
// MySQL
private String mysqlClassName = "com.mysql.jdbc.Driver";
private String mysqlUrl = "jdbc:mysql://localhost:3306/zi" + APPENDED_DB_INFO;
private String mysqlUser = "root";
private String mysqlPassword = "password";
Connection mysqlConnection = null;
public void fetchFromDb2ToMySQL() {
try {
// DB2
Class.forName(db2ClassName);
db2Connection = DriverManager.getConnection(db2Url, db2User, db2Password);
Statement db2Statement = db2Connection.createStatement();
// MySQL
Class.forName(mysqlClassName);
mysqlConnection = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
Statement mysqlStatement = mysqlConnection.createStatement();
ResultSet db2ResultSet = db2Statement.executeQuery("SELECT * FROM sysibm.systables");
while (db2ResultSet.next()) {
int rowId = db2ResultSet.getRow();
String tablename = db2ResultSet.getString(1);
String mysqlSql = String.format("INSERT INTO test VALUE(%d,'%s')", rowId, tablename);
mysqlStatement.addBatch(mysqlSql);
}
mysqlStatement.executeBatch();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if (db2Connection != null && mysqlConnection != null) {
System.out.println("success");
} else {
System.out.println("fail");
}
}
}
public static void main(String[] args) {
DataFetch dataFetch = new DataFetch();
dataFetch.fetchFromDb2ToMySQL();
}
}