How to fetch data from oracle in batches from java in equal batches

谁说胖子不能爱 提交于 2021-02-20 01:48:29

问题


I have a table -

emp_record

which has 40,000 records And I want to fetch the records from java code and below is the requirement -

  1. At a time only 1000 records should be returned
  2. In the next hit next 1000 records
  3. continue till all the records exhaust
  4. The SQL query should not be nested, like

 select *
 from(
 SELECT a.*,rownum rn 
 FROM distributor  a)
 WHERE rn  >= 3000 and rn < 4000; 

Any sort of help is much appreciated.


回答1:


This sounds very artifical as 40.000 records is nothing. I would just read them in one query and perhaps hand them out in batches. In that case you can use statement.setFetchSize(1000) to make the JDBC driver fetch 1000 records at a time and position that as solving the requirement.

Alternatively if you are on Oracle 12 you can use:

select * from distributor
order by something_unique
offset x rows fetch next 1000 rows only

where x is the starting position. It does the same thing as the rownum construction, but with a much nicer syntax.




回答2:


You could use a query that uses ROWNUM by first ordering the rows by a primary key/unique key. Idea from the query here : Best practice for pagination in Oracle?

SELECT * 
  FROM (SELECT A.*, rownum rn
          FROM (SELECT *
                  FROM emp_record
                 ORDER BY pri_key_col) A
         WHERE rownum <= :n * 1000)
 WHERE rn > (:n - 1) * 1000;
  • pri_key_col : Primary key/ unique key column of your table.
  • n : number indicating the batch. If n = 1, it returns first 1000 records ordered that way, n=2 gives next 1000 and so on.


来源:https://stackoverflow.com/questions/50562167/how-to-fetch-data-from-oracle-in-batches-from-java-in-equal-batches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!