oracle表中有2000万条记录通过java程序 如何将数据查询分批出来进行处理然后将数据存入另外一张表中
您可以使用分页查询的方式将数据分批查询出来,然后进行处理,最后将数据存入另外一张表中。以下是一个示例代码:
import java.sql.*;
public class DataProcessing {
private static final int BATCH_SIZE = 1000; // 每批处理的数据量
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 连接数据库
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "username", "password");
stmt = conn.createStatement();
// 查询总记录数
String countQuery = "SELECT COUNT(*) FROM your_table";
rs = stmt.executeQuery(countQuery);
rs.next();
int totalRecords = rs.getInt(1);
// 分批查询数据并进行处理
int totalPages = (int) Math.ceil((double) totalRecords / BATCH_SIZE);
for (int page = 0; page < totalPages; page++) {
int offset = page * BATCH_SIZE;
String dataQuery = "SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY your_column) AS rownum, * FROM your_table) WHERE rownum > " + offset + " AND rownum <= " + (offset + BATCH_SIZE);
rs = stmt.executeQuery(dataQuery);
while (rs.next()) {
// 处理数据
int id = rs.getInt("id");
String name = rs.getString("name");
// ...
// 将数据插入另外一张表中
String insertQuery = "INSERT INTO another_table (id, name) VALUES (" + id + ", '" + name + "')";
stmt.executeUpdate(insertQuery);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
请将jdbc:oracle:thin:@localhost:1521:xe替换为您的Oracle数据库连接字符串,username和password替换为您的数据库用户名和密码。另外,您需要替换your_table为要查询的表名和列名,以及替换another_table为要存入数据的另一张表名和列名。
以上代码使用了分页查询的方式,每次查询BATCH_SIZE条数据,然后进行处理,并将数据插入另一张表中。循环直到所有数据都处理完毕
原文地址: http://www.cveoy.top/t/topic/hAhZ 著作权归作者所有。请勿转载和采集!