get Last Inserted ID from mysql - Java java.sql

Java examples for java.sql:MySQL

Description

get Last Inserted ID from mysql

Demo Code


//package com.java2s;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    static PreparedStatement preparedStatement = null;
    static Connection c = null;

    public static int getLastInsertedID() {
        int lastID = 0;
        ResultSet rs = null;/*www. ja  v a 2s . co  m*/

        try {
            preparedStatement = c
                    .prepareStatement("SELECT last_insert_id() FROM annotation");
            rs = preparedStatement.executeQuery();
            rs.next();
            lastID = Integer.valueOf(rs.getString(1));

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("The last inserted is: " + lastID);
        return lastID;
    }
}

Related Tutorials