Search This Blog

Loading...

Friday, February 5, 2010

How to get auto-generated keys from database using jdbc in java


There are cases that our database insert statements can generate auto-increment ids when we perform executeUpdate() method on our PreparedStatement object. The example given below gives an idea how to get those auto increment ids. After perfoming executeUpdate() method on PreparedStatement, call getGeneratedKeys() method on PreparedStatement. It will return you ResultSet, from which you can get auto increment column values.

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String query = "insert into emps (name, dept, salary) values (?,?,?)";
try{
//get connection object here
conn = Get Connection Object Here;
pstmt = conn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, "Junk Fellow");
pstmt.setString(2, "Junk Dept");
pstmt.setFloat(3, 10000.00);
pstmt.executeUpdate();
rset = pstmt.getGeneratedKeys();
if(rset != null && rset.next()){
System.out.println("Generated Emp Id: "+rset.getInt(1));
}
} catch (SQLException exx) {
exx.printStackTrace();
} finally {
try{
if(conn != null) conn.close();
if(rset != null) rset.close();
if(pstmt != null) pstmt.close();
} catch(Exception ex){
ex.printStackTrace();
}
}

No comments:

Post a Comment