get Last auto generated Id - Java java.sql

Java examples for java.sql:PreparedStatement

Description

get Last auto generated Id

Demo Code


//package com.java2s;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    public static int getLastId(PreparedStatement ps) {
        ResultSet rs = null;//  ww  w .j  av  a 2s  . c  om
        try {
            rs = ps.getGeneratedKeys();
            if (rs != null && rs.next()) {
                return rs.getInt(1);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        } finally {
            closeResultSet(rs);
        }
        return -1;
    }

    public static void closeResultSet(ResultSet rs) {
        if (null != rs) {
            try {
                rs.close();
                rs = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Related Tutorials