0

我在我的 java 程序中使用了一个 select 命令并将其值存储在结果集中。现在在结果集中循环时,我想使用一个选择命令,它将选择结果集的前 5 行并插入到其他表中。第二次,它应该选择接下来的 5 行并插入到表中。第三次,以此类推..

Statement s = connection.createStatement();
s.executeQuery("Select * from table1");
ResultSet res = s.getResultSet();
while(res.next()){
 // here i want to select the first 5 lines of the result set and insert in the second       table
}
4

4 回答 4

1
Statement s = connection.createStatement();
s.executeQuery("Select * from table1");
ResultSet res = s.getResultSet();

while(res.next()){
    // here i want to select the first 5 lines of the result set and insert in the second       table
    while(res.next() && (res.getRow()%5) !=0){
        //select from this table
        //call insert method(what selected)
    }
}
于 2012-11-07T05:35:47.227 回答
0

请添加一个 falg 并使用它

int i=0;

while(res.next() && i< 5){
//select from this table
//call insert method(what selected)
i++;
}
于 2012-11-07T05:21:40.107 回答
0

在while循环内动态创建另一个插入查询并在while循环外执行

于 2012-11-07T05:22:14.780 回答
0

我建议LIMIT使用 PreparedStatement 更改您的查询。就像是:

SELECT * FROM table1 LIMIT ?,?

这有几个优点:

  • 您不会一次性获取所有内容 - 如果您的表格中有很多行要处理,有时可能会带来性能优势
  • 您可以更改预定义要在每个批次中获取的元素数量

所以你的代码看起来像这样:

PreparedStatement ps = null;
ResultSet rs = null;
final int FETCH_LIMIT   = 5; //number of elements to fetch per batch
final int BATCH_LIMIT   = 3; //number of batches you would want

int currentRows = 0;
try{
    ps = connection.prepareStatement("SELECT * FROM table1 LIMIT ?,?");
    for(int currentBatch = 0; currentBatch < BATCH_LIMIT; currentBatch++){
        ps.clearParameters();
        ps.setInt(1, currentRows);
        ps.setInt(2, currentRows + FETCH_LIMIT);

        try{
            rs = ps.executeQuery();
            while(rs.next()){
                // do your work
            }
        }catch(Exception exe){
            //manage exception
        }finally{
            //manage resultset
        }
        currentRows += FETCH_LIMIT;
    }
}catch(Exception exe){
    //Handle your exception
}
finally{
    //Manage your resources
}
于 2012-11-07T05:37:43.833 回答