-1

I'm trying to make unique auto-generated ID using combination of char, date, and value. This is my code :

int getValue;    

public void generateNOS(String query) throws SQLException {
    try {  
        Connection con = koneksi.koneksiDB();
        Statement stm = con.createStatement();
        ResultSet rs = stm.executeQuery(query);
        if (rs.next()) {
            getValue = Integer.parseInt(rs.getString(5));
        }
    } catch (Exception e) {

    }
}
public void autonumberNOS() throws SQLException {
    generateNOS("SELECT count(no_surat)+1 FROM surat_masuk");

    try {
        String NOS = "NOS/1/"+new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+getValue;
        txtNOS.setText(NOS);
    } catch (Exception e) {

    }
}

For example, the ID supposed to "NOS/1/20181120/1". But i got "NOS/1/20181120/0". What was missing ? Is the SQL syntax wrong ? Thanks for any help.

Machavity
  • 30,841
  • 27
  • 92
  • 100
wiryadev
  • 1,089
  • 1
  • 11
  • 33
  • this seems to be asking for duplicate IDs to be created (e.g. in the case of more than one user using the system simultaneously). Better to use an autoincrement field in the DB and get an ID based on that. You can always generate this kind of more user-friendly ID on-demand for display purposes later, based on the data in the table. – ADyson Nov 20 '18 at 14:01

1 Answers1

1

I don't fully follow your code, but I can point out some problems with the JDBC logic. Here is what you are doing right now:

Connection con = koneksi.koneksiDB();
Statement stm = con.createStatement();
String query = "SELECT COUNT(no_surat)+1 FROM surat_masuk";
ResultSet rs = stm.executeQuery(query);
if (rs.next()) {
    getValue = Integer.parseInt(rs.getString(5));
}

It makes no sense to be asking for the fifth column, when your select only has one column in the result set. You should probably be going after the first column index, i.e.

if (rs.next()) {
    getValue = rs.getInt(1);
}

Note also that I am using ResultSet#getInt() here, rather than ResultSet#getString(), because the count would typically be represented by an integer at the database level.

An alternative to requesting the first column index would be to give the count term an alias, and then access that:

String query = "SELECT COUNT(no_surat) + 1 AS cnt FROM surat_masuk";
ResultSet rs = stm.executeQuery(query);
if (rs.next()) {
    getValue = rs.getInt("cnt");
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360