-2

古いスキーマからデータをインポートして変換し、新しいスキーマにデータを挿入する Java プログラムを使用して、大規模で多様なデータセットを実行しています。プログラムはパイロット データで正常にテストされましたが、実際のデータでは例外がスローされています。

データセット全体でスローされた例外の数を数え、どのレコードが例外をスローしているかをログに記録できるようにしたいと考えています。誰かがこれを行う方法を教えてもらえますか?

現状では、プログラムは最初の例外にヒットしたときに現在クラッシュしているため、コードがデータセットを最後まで処理できた場合に例外が 1 つになるか、1,000 個になるかはわかりません。

以下のコードの関連する側面を囲んでいます。カウントと ClientNumber に注意しながら例外をスキップするように変更するにはどうすればよいですか?

try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection sourceConn = DriverManager.getConnection("jdbc:odbc:source_db");
    Statement st = sourceConn.createStatement();
    Connection destinationConn = DriverManager.getConnection("jdbc:odbc:destination_db");

    int ClientNumber;
    String Name;
    ResultSet rest = st.executeQuery("SELECT * FROM sourceTable");
    PreparedStatement ps5 = null;
    PreparedStatement ps6 = null;
    PreparedStatement ps7 = null;
    PreparedStatement ps8 = null;
    while(rest.next()){
        ClientNumber = rest.getInt(1);
        Name = rest.getString(2);//plus other variables skipped here for brevity
        ps5 = destinationConn.prepareStatement(
            "INSERT INTO Clients ("
            + "ClientNumber, Name) "
            +"VALUES (?, ?)"
            );
        ps5.setInt(1, ClientNumber);
        ps5.setString(2, Name);
        ps5.executeUpdate();
        //some other stuff for ps6,ps7,ps8
        destinationConn.commit();
    }
    //ps5.close();
}
catch (ClassNotFoundException cnfe){cnfe.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
4

2 に答える 2

2

これはどうですか、ループを別の方法で書くだけです:

try {
    // TODO: write your setup code here

    boolean hasNext = false;
    try {
        hasNext = rest.next();
    }catch (Exception e) {
        // TODO: log exception, increase a counter
    }
    while(hasNext){
        try {
            // TODO: write your processing code here

        }catch (Exception e) {
            // TODO: log exception, increase a counter
        }
        try {
            hasNext = rest.next();
        }catch (Exception e) {
            // TODO: log exception, increase a counter
            hasNext = false; //prevent infinite loops
        }
    }
} catch (Exception e){
    // TODO: this should never happen, handle ClassNotFoundException etc.
}

更新: 次のように、 next() を 2 回呼び出す必要がなくなります。

try {
    // TODO: write your setup code here

    while(true){
        try {
            if(!rest.next()){
                break;
            }
        }catch (Exception e) {
            // TODO: log exception, increase a counter
            break;
        }
        try {
            // TODO: write your processing code here

        }catch (Exception e) {
            // TODO: log exception, increase a counter
        }
    }
} catch (Exception e){
    // TODO: this should never happen, handle ClassNotFoundException etc.
}
于 2013-10-13T18:28:37.887 に答える