get Next Id - Java JDBC

Java examples for JDBC:Table

Description

get Next Id

Demo Code


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

public class Main {
    public static int getNextId(Connection con, String fieldId, String table)
            throws SQLException {
        String query = "SELECT MAX(".concat(fieldId).concat(") FROM ")
                .concat(table);//from  w  w w.  java2s  .  c om
        PreparedStatement stmt = con.prepareStatement(query);
        ResultSet rs = stmt.executeQuery();
        return rs.next() ? rs.getInt(1) + 1 : 1;
    }
}

Related Tutorials