Welcome to my blog, hope you enjoy reading
RSS

Tuesday 12 February 2013

MYSQL: Get the Auto-Increment Values after Insert Statement

MYSQL: Get the Auto-Increment Values after Insert Statement

In general, the PRIMARY KEY field is the AUTO_INCREMENT field. Now wen you insert a row, a new key is generated and you can’t get it through usual way as this row can be accessed only using the primary key.
So here is how it can be done:


package com.javanotes2all.java.sql;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class GetAutoGeneratedKey { public static void main(String[] args) { try { //table in database /*CREATE TABLE IF NOT EXISTS `test` ( `testid` int(11) NOT NULL AUTO_INCREMENT, `testname` varchar(50) NOT NULL, `testname1` varchar(50) NOT NULL, PRIMARY KEY (`testid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; */ Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "****"); String sql="INSERT INTO `test`(`testname`, `testname1`) VALUES ('a','aa')"; /** * using statement */ Statement stmt=con.createStatement(); stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys(); int autoIncValue = -1; if(rs.next()) { autoIncValue = rs.getInt(1); /*You can get more generated keys if they are generated in your code*/ } System.out.println(autoIncValue); /** * using preparedstatement */ PreparedStatement ps=con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); ps.executeUpdate(); rs=ps.getGeneratedKeys(); autoIncValue = -1; if(rs.next()) { autoIncValue = rs.getInt(1); /*You can get more generated keys if they are generated in your code*/ } System.out.println(autoIncValue); }catch(Exception e) { System.out.println(e); } } }

0 comments: