我是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);
}
}
}
答案 0 :(得分:1)
一次获取100行:
PreparedStatement pstmt = con1.prepareStatement(sql);
((OraclePreparedStatement)pstmt).setExecuteBatch(100); // <-- Add this
ResultSet rs = statement.executeQuery("SELECT * FROM groups");
一次插入100行:
pstmt.executeUpdate()
...以上内容将改变((OraclePreparedStatement)pstmt).sendBatch(); // <-- This ensures that any queued inserts get sent to the database.
con.close();
con1.close();
的行为,以便累积插入内容,并在达到批量大小后将其发送到数据库。
您还需要进行一次最后的小改动,以确保始终发送最后一批产品:
"search.exclude": {
"**/node_modules": false,
"node_modules": true
}
文档链接: