【发布时间】: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()等版本。