Kill Sybase processes using batch with java jdbc



I used Java to create a simple database process killer by sending a kill command in a loop. I want to know if I can use batch with kill command in one call:

try(Connection dbCon = GetDBConnection()){
    try (Statement st = dbCon.createStatement();) { 
        dbCon.setAutoCommit(false);
        for (int i = 0; i < processes.length; i++) {
            st.addBatch("kill " + processes[i]);
        }
        st.executeBatch(); 
        dbCon.commit();
        dbCon.setAutoCommit(true);
    } 
    catch (Exception e) {
        System.out.println("Error SQL killing process: " + e);
    }
catch (Exception e) {
    System.out.println("Error opening connection: " + e);
}

Answer

I have the chance to try it and worked.

I have add some little changes to validate if it is only one process make a normal kill, and if it get more than one, then use batch.

try (Connection dbCon = GetDBConnection(); Statement st = dbCon.createStatement();) {
    String queryKill = "kill ";
    if (spids.length > 1) {
        dbCon.setAutoCommit(false);

        for (int i = 0; i < spids.length; i++) {
            st.addBatch(queryKill + spids[i]);
            System.out.println(queryKill + spids[i]);
        }

        st.executeBatch();
        dbCon.commit();
        dbCon.setAutoCommit(true);
    } else {
        queryKill = queryKill + spids[0];
        System.out.println(queryKill + spids[0]);
        st.execute(queryKill);
    }
} catch (Exception e) {
    killed = false;
    System.out.println("Error SQL killing process: " + e);
}


Source: stackoverflow