![](/img/trans.png)
[英]Copy records of a person from one database to another database - Oracle and Java
[英]select from one oracle database and batch insert in another oracle database using java
我是Java编程的初学者。 我试图使用下面的Java代码从一个Oracle数据库表中获取数据并插入到另一个数据库表中,这是成功的。 但是我不知道在此代码中实现批处理插入逻辑和增加的提取大小。 任何人都可以帮助。 我的目标是一次往返获取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);
}
}
}
一次获取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();
文档链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.