0

Javaプログラムでselectコマンドを使用し、その値を結果セットに保存しました。結果セットをループしているときに、結果セットの最初の5行を選択して、他のテーブルに挿入するselectコマンドを使用したいと思います。2回目は、次の5行を選択して、テーブルに挿入する必要があります。そして3回目など。

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

ファルグを追加して使用してください

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

LIMITPreparedStatementを使用してクエリを変更することをお勧めします。何かのようなもの:

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 に答える