Fajar Syairillah
Fajar Syairillah

Reputation: 93

How To Make Auto Increment Number Java

I'm making method for automatic number but this number is stuck only to number P-011. How to fix it ?

private void outomatic_number(){
        try {
            open_db();
            String sql="select right (no_rm,2)+1 from pasien";
            ResultSet rs=stm.executeQuery(sql);
            if(rs.next()){
                rs.last();
                String no=rs.getString(1);
                while (no.length()<3){
                    no="00"+no;
                    txtno.setText("P-"+no);}
                }
            else
            {
               txtno.setText("P-001"); 
            }
            } catch (Exception e) 
            {
        }
    }

Upvotes: 0

Views: 298

Answers (2)

pratik patel
pratik patel

Reputation: 326

it is not necessary that last element of ResultSet is the highest number of it. Instead of these you can use "order by desc". It will return the las number first then take first element of it.

Upvotes: 0

Andreas
Andreas

Reputation: 159175

Since you call rs.last(), it seems likely that there is more than one record in pasien.

You need to remember that a SQL SELECT statement returns data in arbitrary order if there is no ORDER BY clause.

Since you don't have an ORDER BY clause, the "last" record is not necessarily the record with the highest number.

Add an ORDER BY clause to fix the code.

Upvotes: 1

Related Questions