http://feeds.feedburner.com/SpendYourTimeHere-Once

Current Affiares

Monday, August 13, 2012

How to get the max value of a primary key field in java

How to get the max value of a primary key field in java?

// in java file


package testlab.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.jdbc.core.JdbcTemplate;


public class TestlabUtilsDb {

    private JdbcTemplate jdbcTemplate;

  
    public  void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
// maxquery could be select Max(id) as id from tablename

    public  int maxId(String maxquery) {
        int maxid = 0;
        PreparedStatement pstmt = null;
        Connection con = null;
        ResultSet rs;
        try {
            con = jdbcTemplate.getDataSource().getConnection();
            pstmt = con.prepareStatement(maxquery);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                maxid = rs.getInt(1);
            }
            if (maxid == 0) {
                maxid = 1;
            } else {
                maxid = (maxid + 1);
            }
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException ex) {
                    Logger.getLogger(TestlabUtilsDb.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ex) {
                    Logger.getLogger(TestlabUtilsDb.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return maxid;

    }
}

No comments:

Post a Comment

My Blog List

Popular Posts

All Rights Reserved To SYTHONCE. Ethereal theme. Powered by Blogger.