[Solved] How to check that there is a record in Database? [closed]


It is all about primary key AND foreign key. If you want to add a record with an id, that must exist in another table, it is a foreign key.

If you don’t want this you can do the following:

conn = getConnection();
String query = "SELECT EXISTS(SELECT NULL FROM my_table WHERE number = ? LIMIT 1)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, myId); // Or setInt or whatever
rs = pstmt.executeQuery();
if (rs.next()) {
    boolean exists= rs.getBoolean(1);
    System.out.println("exists= " + exists);
} else {
    System.out.println("error: could not get the record counts");
}

I edited my answer because, the query provided by: @eggyal is faster

solved How to check that there is a record in Database? [closed]