I'm going through some code and trying to figure out how to get rid of duplicates from the following two methods. Both methods execute a simple login/register query to a local MySQL DB. I couldnt figure out a good design pattern to solve my problem, especially to get rid of the duplicate try-catch.
Any advice?
public class DatabaseHandler {
[...]
public static boolean checkLogin(String username, String password) {
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "select * from users where username = ? and password = ? ";
try {
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
return result.next(); //True if User exists
} catch(SQLException e) {
return false;
} finally {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static boolean registerUser(String username, String password) {
Connection connection = createConenction();
PreparedStatement statement = null;
String query = "insert into users (username, password) values (?, ?)";
try {
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
statement.executeUpdate();
return true;
} catch(SQLException e) {
return false;
} finally {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```