Search code examples
mysqlnetbeansuniqueautonumber

Value Always Set to 0 instead of 1 When Creating Auto-Generated ID in Netbeans


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.


Solution

  • 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");
    }