2016-03-18 58 views
-1

如何從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(); 
} 
} 
+0

安卓在控制檯中出現什麼錯誤? – hurricane

回答

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(be導致它通常比聲明更快,更安全)

+0

你好你明白我的問題嗎? – ASHOK

相關問題