java - Best way to find out if user is already registered -
how find out, user registered, e.g. in web application? have database of 1 million users. every time comparing every single row in database inefficient. there other optimal approach?
every time comparing every single row in database inefficient
i gather you're hauling entire db table contents java's memory select * user , looping on every row in while loop , comparing username equals() below, true?
public boolean exists(string username) throws sqlexception { // ... declare, etc. statement = connection.preparestatement("select * user"); resultset = statement.executequery(); while (resultset.next()) { if (username.equals(resultset.getstring("username"))) { return true; } } return false; // ... close, etc (in finally!) } then that's indeed inefficient. should indexing username column (it is, unique constraint) , make use of sql where clause. it'll return 0 or 1 rows , db best finding it, much, faster above java approach.
public boolean exists(string username) throws sqlexception { // ... declare, etc. statement = connection.preparestatement("select id user username = ?"); statement.setstring(1, username); resultset = statement.executequery(); return resultset.next(); // ... close, etc (in finally!) } in nutshell, long make proper use of db indexes , write sql queries such returns exactly information need, without necessity filtering using java or additional queries afterwards, it'll efficient approach.
Comments
Post a Comment