简体   繁体   English

从结果集中选择几行mysql java

[英]select few rows from resultset mysql java

i have used a select command in my java program and stored its value in the result set. 我在Java程序中使用了select命令,并将其值存储在结果集中。 now while looping in the resultset i want to use a select command which will select the first 5 lines of the resultset and insert into other table. 现在,在循环结果集时,我想使用选择命令,该命令将选择结果集的前5行并插入其他表中。 for the second time, it should select the next 5 lines and insert into the table. 第二次,它应该选择接下来的5行并插入到表格中。 and for the third time, so on.. 第三次,如此等等。

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
}
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)
    }
}

Please add a falg and use that is it 请添加一个falg并使用它

int i=0;

while(res.next() && i< 5){
//select from this table
//call insert method(what selected)
i++;
}

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

I would suggest changing your query using LIMIT and using a PreparedStatement. 我建议使用LIMIT和PreparedStatement更改查询。 Something like: 就像是:

SELECT * FROM table1 LIMIT ?,?

This has a couple of advantages: 这有两个优点:

  • You are not fetching everything in one shot - can be sometimes a performance benefit if you've a lot many rows to deal with in your table 您并非一口气获取所有内容-如果表中要处理的行很多,有时可能会提高性能
  • You can change pre-define the number of elements that you want to fetch in every single batch 您可以更改预定义的每批中要获取的元素数量

So your code will look something like this: 因此,您的代码将如下所示:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM