从jdbc中的多个数据库中插入两个表

时间:2016-03-18 11:05:16

标签: mysql jdbc

如何从jdbc中的两个数据库插入两个表是否可能?

我有代码但不能正常工作

public class MergeData {
static {
     try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } 
}
@SuppressWarnings("unchecked")
public static void main(String[] args) throws SQLException {
    //"jdbc:mysql://localhost:3306/fhv1", "root", "root"
    DBDataFetcher database1 = new DBDataFetcher("jdbc:mysql://localhost:3306/fhv1", "root", "root");
    List<Object> restDetailsList = (List<Object>) database1.fetchTableRows("restdetails");
    database1.closeConnection();
    long restid = 0;
    for(Object obj : restDetailsList) {
        if (obj instanceof RestDetails) {
            restid = ((RestDetails) obj).getRest_id();
            System.out.print(restid + " ");
        }

    }

    DBDataFetcher database2 = new DBDataFetcher("jdbc:mysql://localhost:3306/test", "root", "root");
    List<Object> restLocationList = (List<Object>) database2.fetchTableRows("restlocation");
    database2.closeConnection();
    for(Object obj : restLocationList) {
        if (obj instanceof RestLocation) {
            ((RestLocation) obj).setRest_id(++restid);
            System.out.print(((RestLocation) obj).getRest_id() + " ");
            restDetailsList.add(obj);

        }

    }

    DBDataMerger merger = new DBDataMerger("jdbc:mysql://localhost:3306/db", "root", "root");
    merger.mergeTable(restDetailsList, "restdetails");
    merger.closeConnection();
}
}

1 个答案:

答案 0 :(得分:0)

在普通JDBC中,您应该创建两个连接(每个数据库一个)

public Connection getDbConnection(String dbUrl, String driver, String     user, String psw){
Connection conn=null;
try{

Class.forName(driver);
conn = DriverManager.getConnection(dbUrl,user,psw);
 }catch(SQLException e){
//log exception
}
return conn;
}

要插入记录,您可以执行类似

的操作
  public void insertRecord(){
//add try and catch/finally

//inserting into 1st DB
Connection conn1 = getDBConnection(dbURl1, driver1, user1, psw1);
Statement stmt = conn1.CreateStatement();
String insert1 = "insert into tbl1 (a,b,c) values(1,2,2);
stmt.executeUpdate(insert1);

//inserting into 2nd DB
Connection conn2 = getDBConnection(dbURl2, driver2, user2, psw2);
stmt = conn2.CreateStatement();//reassing statement or use a new one
String insert2 = "insert into tbl2 (a,b,c) values(1,2,2);
stmt.executeUpdate(insert2);

}

通常,您需要使用PreaparedStatement而不是Statement(因为它通常比Statement更快,更安全)

相关问题