// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class OracleGenerateKey2 {
    public static void main(String[] args) throws Exception {
        Handler h = new ConsoleHandler();
        h.setLevel(Level.ALL);
        h.setFormatter(new SimpleFormatter());
        Logger.getLogger("oracle").addHandler(h);
        Logger.getLogger("oracle").setLevel(Level.ALL);
        System.setProperty("oracle.jdbc.Trace", "true");
        Class.forName("oracle.jdbc.OracleDriver");
        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "arne", "hemmeligt");
        con.setAutoCommit(true);
        Statement stmt = con.createStatement();
        stmt.executeUpdate("CREATE SEQUENCE test_seq1 START WITH 1");
        stmt.executeUpdate("CREATE SEQUENCE test_seq2 START WITH 2");
        stmt.executeUpdate("CREATE TABLE test_tbl(id1 NUMBER NOT NULL, id2 NUMBER NOT NULL, s VARCHAR2(50), PRIMARY KEY(id1))");
        PreparedStatement pstmt = con.prepareStatement("INSERT INTO test_tbl VALUES(test_seq1.NEXTVAL, test_seq2.NEXTVAL, 'XXX')", new String[] { "id1", "id2" });
        pstmt.executeUpdate();
        ResultSet rs = pstmt.getGeneratedKeys();
        while(rs.next()) {
            System.out.println(rs.getLong(1) + " " + rs.getLong(2));
        }
        stmt.executeUpdate("DROP TABLE test_tbl");
        stmt.executeUpdate("DROP SEQUENCE test_seq1");
        stmt.executeUpdate("DROP SEQUENCE test_seq2");
        stmt.close();
        con.close();
    }
}
