萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> 利用Java技術搞定兩個不同數據庫之間的數據交換

利用Java技術搞定兩個不同數據庫之間的數據交換

 1、建立遠程數據庫的連接:

    public static synchronized Connection getConFromRemote() {
        Connection con = null;
        String url = "jdbc:sqlserver://admin.xxx.xxx.comdbo:1436;databaseName=remote_jadepool";
        String userName = "hkm12345";
        String password = "pwd12345";
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = DriverManager.getConnection(url, userName, password);
        } catch (SQLException ex1) {
            ex1.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return con;
    }

2、建立本地數據庫的連接

    public static synchronized Connection getConFromLocal() {
        Connection con = null;
        String url = "jdbc:sqlserver://127.0.0.1dbo:1436;databaseName=jadepool";
        String userName = "hkm123";
        String password = "pwd123";
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = DriverManager.getConnection(url, userName, password);
        } catch (SQLException ex1) {
            ex1.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return con;
    }

3、將遠程數據庫的數據保存到本地數據庫中

    public void backupDB() {
        Jade j0 = new Jade(getConFromRemote(), cn.jadepool.sql.DbConnectionType.USING_DB_01);
        List<Map> v0 = j0.query("select * from jade_book");
        List<Map> v1 = j0.query("select * from jade_book_cs");
        j0.commit();
        
        Jade j1 = new Jade(getConFromLocal(), cn.jadepool.sql.DbConnectionType.USING_DB_02);
        j1.delete("delete from jade_book");
        j1.insert("jade_book", v0);
        j1.delete("delete from jade_book_cs");
        j1.insert("jade_book_cs", v1);
        j1.commit();
    }
    

這裡演示的是兩相同的數據庫,使用不同的數據庫不影響結果,但兩者表的結構一定要一致。

copyright © 萬盛學電腦網 all rights reserved