如何将结果集数据转储到数据库表中

时间:2013-08-21 14:17:28

标签: java sql

我正在通过SQL查询('SELECT_PROCESS_INITIAL_REQUEST')创建一个结果集,它基本上只是抓取SQL数据库表中的所有内容。

Statement stmt = conn.createStatement();
String sql = SQLDataAdaptor.SELECT_PROCESS_INITIAL_REQUEST;
ResultSet rsRequest = stmt.executeQuery(sql);

然后,我想将该数据转储到与原始数据相同的表中,但是在不同的数据库中。我该怎么做?

2 个答案:

答案 0 :(得分:0)

将其转储到另一个数据库意味着Java必须处理您的结果集。所以我担心你必须以编程方式这样做。

想想“预备语句”,“添加批处理方法”,不要忘记每n条记录执行一次插入。

答案 1 :(得分:0)

使用Java Tutorial Website上的示例 -

public static void viewTable(Connection con, String dbName)
throws SQLException {

    //Modify this code according to 2nd database vendor and credentials- 
            String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection conn2 = DriverManager.getConnection(url);

    Statement stmt = null;
    Statement insertStmt = null;
    String query = "select COF_NAME, SUP_ID, PRICE, " +
               "SALES, TOTAL " +
               "from " + dbName + ".COFFEES";
    try {
        stmt = con.createStatement();
        insertStmt = conn2.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
            int sales = rs.getInt("SALES");
            int total = rs.getInt("TOTAL");

            String insertQuery = "INSERT INTO COFFEES (COF_NAME, SUP_ID, PRICE, sales, total) VALUES (coffeeName,supplierID, proce, sales, total);

           try{
               insertStmt.execute(insertQuery);

           }catch(SQLExeption e){
                e.printStackTrace();
           }
         }
    } catch (SQLException e ) {
        e.printStackTrace();
    } finally {
        if (stmt != null) { stmt.close();}
        if(insertStmt != null) {insertStmt.close();}
    }
}
相关问题