Refer the below example to get the Auto generated emp_id column value using JDBC.Get the Statement from Jdbc Connection. Statement object use to sending SQL statements to the database.
Statement statement = connection.createStatement();
Executes the below program, Which insert the record in the trn_employee table. After record insertion it return the auto generated primary key value
statement.executeUpdate("INSERT INTO trn_employee (EMP_NAME, EMP_SALARY) VALUES('Manish',19000)");
getGeneratedKeys() method returns the ResultSet object and from that we retrive the primary key number.
package com.net.example;
import java.sql.*;
public class JdbcAutoGeneratedKeyExample {
public static void main(String[] args) {
JdbcAutoGeneratedKeyExample jdbcMysqlSelectExample = new JdbcAutoGeneratedKeyExample();
Connection connection = jdbcMysqlSelectExample.getConnection();
Statement statement = null;
ResultSet rs = null;
try {
statement = connection.createStatement();
statement.executeUpdate("INSERT INTO trn_employee (EMP_NAME, EMP_SALARY) VALUES('Manish',19000)");
rs = statement.getGeneratedKeys();
if (rs.next()) {
System.out.println("Auto Generated Primary Key " + rs.getInt(1));
}
} catch (SQLException e) {
System.out.println("SQLException Occured..");
} finally {
try {
if (rs != null) {
rs.close(); // close result set
}
if (statement != null) {
statement.close(); // close statement
}
if (connection != null) {
connection.close(); // close connection
}
} catch (SQLException e) {
System.out.println("SQLException Occured..");
}
}
}
/***
* Get Connection
*
* @return
*/
private Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/technicalkeeda", "root", "");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException Occured...");
} catch (SQLException e) {
System.out.println("SQLException Occured...");
}
return connection;
}
}
Note : On Every execution of program , it generates next auto incremented number.
Auto Generated Primary Key 13
Hi I am Yashwant founder of www.technicalkeeda.com, Purpose of this website to share the programming knowledge in the form post , blogs and articles.