Share on Google+Share on Google+

JDBC: Last Inserted Id Example

Advertisement
In this tutorial, you will learn how to find last inserted record ID using JDBC API.

JDBC: Last Inserted Id Example

In this tutorial, you will learn how to find last inserted record ID using JDBC API.

Getting Last Inserted ID : Last inserted Id is required for further insertion, so that you use correct id for next insertion.  you can get the last inserted id by using MAX(), writing query as -

 sql = "SELECT MAX(roll_no) from student";

Example :  In this example we are finding the roll_no of last inserted record of student table.

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class LastInsertId {
	public static void main(String[] args) {
		System.out.println("Last inserted Id Example...");
		Connection con = null;
		Statement statement = null;
		ResultSet rs = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			// Connecting to the database
			Class.forName(driverName);
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {
				// Creating object of Statement
				statement = con.createStatement();

				// Finding id of last inserted record
				String sql = "SELECT MAX(roll_no) from student";
				rs = statement.executeQuery(sql);
				while (rs.next()) {
					System.out.println("Id of Last inserted student record : "
							+ rs.getInt(1));
				}
			} catch (SQLException e) {
				System.out.println(e);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output :

Last inserted Id Example...
Id of Last inserted record : 7

Advertisements

Posted on: September 28, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.