我在java程序中使用了select命令并将其值存储在结果集中。现在,当在结果集中循环时,我想使用一个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
}
答案 0 :(得分: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)
}
}
答案 1 :(得分:0)
请添加一个标志并使用它
int i=0;
while(res.next() && i< 5){
//select from this table
//call insert method(what selected)
i++;
}
答案 2 :(得分:0)
在while循环内动态创建另一个插入查询,并在while循环外执行
答案 3 :(得分: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
}