对于java中的循环,在数据库中的一系列记录中

arj*_*unj 0 java mysql loops

我有两个id,它们对应于数据库中的一系列记录.我想分批处理1000个记录.让我们说两个id是51234和59265.我想循环这个并确保所有记录都被处理.

我从下面的for循环开始

for(int i = 51234; i < 59265; i= i+1000) {

select * from database where id between i and i+1000;
//do the stuff
}
Run Code Online (Sandbox Code Playgroud)

现在这个工作正常,直到59234记录,最近的31条记录怎么样?我想在这次运行中处理它们.

我可能可以在每次迭代中检查i的值是什么,并检查在查询中添加1000是否超过最大id并调整sql查询.这是唯一的方法吗?for循环是正确的方法吗?

Bra*_*rby 5

   int batchSize=1000;
   for(int i = 51234; i <= 59265; i+=batchSize) {        
    select * from database where id between i and Math.min(i+batchSize, 59265);
    //do the stuff
    }
Run Code Online (Sandbox Code Playgroud)

样本输出:

between 51234 and 52234 actualBatch=1000
between 52234 and 53234 actualBatch=1000
between 53234 and 54234 actualBatch=1000
between 54234 and 55234 actualBatch=1000
between 55234 and 56234 actualBatch=1000
between 56234 and 57234 actualBatch=1000
between 57234 and 58234 actualBatch=1000
between 58234 and 59234 actualBatch=1000
between 59234 and 59265 actualBatch=31
Run Code Online (Sandbox Code Playgroud)

由于介于两者之间,因此每批次都有重叠.你可以改变它并使用不等式来解决这个问题:

 int batchSize = 1000;
 int start=51234;
 int end=59265;
 for(int i = start; i < end + 1; i+=batchSize) {
   select * from database where id >= i and id < Math.min(i+batchSize, end);
 } 
Run Code Online (Sandbox Code Playgroud)

样本输出:

id >= 51234 and id < 52234 actualBatch=1000
id >= 52234 and id < 53234 actualBatch=1000
id >= 53234 and id < 54234 actualBatch=1000
id >= 54234 and id < 55234 actualBatch=1000
id >= 55234 and id < 56234 actualBatch=1000
id >= 56234 and id < 57234 actualBatch=1000
id >= 57234 and id < 58234 actualBatch=1000
id >= 58234 and id < 59234 actualBatch=1000
id >= 59234 and id < 59266 actualBatch=32
Run Code Online (Sandbox Code Playgroud)