How to get value of a serial field after INSERT?

By Alvin J. Alexander, devdaily.com

Assuming:

  • you have *just* done an INSERT into a table named order,
  • the name of the sequence for that table is order_order_id_seq
  • you are using the Java programming language
to get the value of the serial number just created, use some code like this:

  // assume we have a database connection named "connection"
  int serialNum = 0;
  Statement stmt = connection.createStatement();
  String query = "select currval('order_order_id_seq')";
  ResultSet rs = stmt.executeQuery(query);
  if ( rs.next() )
  {
    serialNum = rs.getInt(1);
    System.out.println( "serialNum = " + serialNum );
  }
  stmt.close();
  connection.close();

Katz!


devdaily logo