【问题标题】:select from one oracle database and batch insert in another oracle database using java使用java从一个oracle数据库中选择并批量插入另一个oracle数据库
【发布时间】:2015-07-07 18:27:11
【问题描述】:

我是 Java 编程的初学者。 我正在尝试从一个 oracle 数据库表中获取数据并使用下面的 java 代码插入到另一个数据库表中并且它是成功的。但是我不知道在此代码中实现批量插入逻辑并增加获取大小。任何人都可以帮忙。我的目标是在一次往返中获取 100 行并插入 100 行,而不是一一插入。提前致谢。

import java.sql.*;
import java.io.*;
import java.util.*;


public class Dbtodb {
    public static void main(String[] args) {
        try
{
Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@ipaddress1:port1:server1","user1","password1");
Connection con1 = DriverManager.getConnection( "jdbc:oracle:thin:@ipaddress2:port2:server2","user2","password2");
String sql = "INSERT INTO test_GROUPS("+ "GROUP_NO,"+ "GROUP_NAME,"+ "BUYER,"+ " MERCH,"+" DIVISION)"+ "VALUES(?,?,?,?,?)";
Statement statement = 
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);  
PreparedStatement pstmt = con1.prepareStatement(sql);
ResultSet rs = statement.executeQuery("SELECT * FROM groups"); 
while ( rs.next() )  
{  
    int gpnum = rs.getInt(1);
String gpname = rs.getString(2);
    int byr = rs.getInt(3);
    int merch = rs.getInt(4);
    int divisn = rs.getInt(5);
pstmt.setInt(1, gpnum);       
pstmt.setString(2, gpname);
pstmt.setInt(3, byr);          
pstmt.setInt(4, merch);   
pstmt.setInt(5, divisn);   
pstmt.executeUpdate();
} 
con.close();
con1.close();
}
catch (SQLException e)
{
System.out.println("could not get JDBC connection: " +e); 
}

    }
}

【问题讨论】:

  • 不是答案,但是:您不应该将SELECT * 与通过索引从ResultSet 获取元素混为一谈。不保证SELECT * 返回ResultSet 中的列的顺序。要么明确列出查询字符串中的列,要么使用采用列名的rs.getInt() 等版本。

标签: java database oracle


【解决方案1】:

一次获取 100 行:

ResultSet rs = statement.executeQuery("SELECT * FROM groups");
rs.setFetchSize(100); // <-- Add this to fetch 100 rows at a time.

一次插入 100 行:

PreparedStatement pstmt = con1.prepareStatement(sql);
((OraclePreparedStatement)pstmt).setExecuteBatch(100); // <-- Add this
ResultSet rs = statement.executeQuery("SELECT * FROM groups"); 

...以上将改变pstmt.executeUpdate() 的行为,因此它会累积插入,并且仅在达到批量大小时才将它们发送到数据库。

您还需要最后一点更改,以确保您的最后一批总能送出:

((OraclePreparedStatement)pstmt).sendBatch(); // <-- This ensures that any queued inserts get sent to the database.
con.close();
con1.close();

文档链接:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    相关资源
    最近更新 更多