-2

In java, say I have a program which checks for the max value in database and increments it by 1 to create my receipt number.

How could I start my first number as 001 and increment it accordingly.

Thus

int x = rs.get( sql statement for maximum value). 

Say x = 001

New number to be inserted back should be 002.

Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
Victor Ikenna
  • 45
  • 1
  • 8

1 Answers1

2

First of all, your variable x is int, so it can't be 001, just 1, but you can make a String to use it elsewhere with formatting:

String formattedX = String.format("%03d", x);

I suppose, "checks for the max value in database" means to get next value for the Primary Key. To do it, you can use a database sequence (read about it here, it's databasespecific so I can't say how to implement it in your case) and everytime you need it, get it's next value. For OracleDB it can be done with this query:

SELECT somesequense.nextval FROM DUAL;

Or you can use a analytics MAX() functions for your Database, example for Oracle:

SELECT MAX(receipt_number) "Maximum" FROM receipts;

And then just increment it in your java code. But it's not a good solution, because it can lead to some problems, when you'll get the same value in several transactions.

Community
  • 1
  • 1
Stanislav
  • 27,441
  • 9
  • 87
  • 82