How to get value of Auto Increment column value in java?

UPDATED: 18 September 2011
Database


We are creating so many application and we have to create it with proper way. If you creating application that uses Database. Then you have to keep in mind some basic rules before you go further.

  • Database design must be good - that help you to decrease the transaction count with database.
  • Use auto Increment column rather than using simple column for IDs.

Simple User:
  • Insert Column using (Database call)
  • select maximum id from table. (Database call)

Advance User:
  • Insert row and get return value of that inserted row.

Simple user uses typical logic of database but java support some feature that helps you lot. Below code give you the idea how Advance User saves time and less transaction.
Connection con = DriverManager.getConnection(Host, Username, Password);
Statement smt = con.createStatement();
boolean _generate = smt.execute("insert into test values(0);", smt.RETURN_GENERATED_KEYS);
ResultSet rs = smt.getGeneratedKeys();
if (rs.next()) {
 ID = rs.getInt(1);
}

0 comments :