JDBC always tests the last row of MySQL table?

后端 未结 2 741

I have a Manager class that saves data in the SQL table and also get result from SQL table and test these data.when I run my program,one frame will be shown that gets ID and pas

2条回答
  •  再見小時候
    2021-01-23 18:25

    Because you're hauling the entire database table down into Java's memory and testing every row in a while loop. You don't break the loop if a match is found so that it continues overwriting the boolean outcome until with the last row.

    That said, you really don't want to do the comparison in Java. Just make use of the SQL WHERE clause. That's much more efficient and really the task a DB is supposed to do. Don't try to take over the DB's work in Java, it's only going to be inefficient.

    public boolean exists(String username, String password) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        boolean exists = false;
    
        try {
            connection = database.getConnection();
            preparedStatement = connection.prepareStatement("SELECT id FROM client WHERE username = ? AND password = ?");
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            resultSet = preparedStatement.executeQuery();
            exists = resultSet.next();
        } finally {
            close(resultSet);
            close(preparedStatement);
            close(connection);
        }
    
        return exists;
    }
    

    You see that I made a few enhancements:

    1. Use preparedstatement.
    2. Do not use equalsignorecase. A password of "FooBar" should NOT be the same as "foobar".
    3. Gently acquire and close resources in same scope to avoid leaking.
    4. Have it in an independent and reuseable non-static DAO method.

    To learn more about using JDBC the proper way you may find this basic tutorial useful.

提交回复
热议问题