// 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 OracleGenerateKey {
    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_seq START WITH 1");
        stmt.executeUpdate("CREATE TABLE test_tbl(id NUMBER NOT NULL, s VARCHAR2(50), PRIMARY KEY(id))");
        //PreparedStatement pstmt = con.prepareStatement("INSERT INTO test_tbl VALUES(test_seq.NEXTVAL, 'XXX')", PreparedStatement.RETURN_GENERATED_KEYS);
        PreparedStatement pstmt = con.prepareStatement("INSERT INTO test_tbl VALUES(test_seq.NEXTVAL, 'XXX')", new String[] { "id" });
        pstmt.executeUpdate();
        ResultSet rs = pstmt.getGeneratedKeys();
        while(rs.next()) {
            //System.out.println(rs.getRowId(1));
            System.out.println(rs.getLong(1));
        }
        stmt.executeUpdate("DROP TABLE test_tbl");
        stmt.executeUpdate("DROP SEQUENCE test_seq");
        stmt.close();
        con.close();
    }
}
