I'm creating a basic register/login username/password database and I'm wondering if my approach is correct. I'm not satisfied with code just working, I want it to be clean and efficient as well.
Users can access an internet login page, enter credentials, and basically log in. I have a Database class, which creates accounts and checks if the credentials entered are correct.
So, the Database class:
public class Database {
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
// Method for registering a new account. Credentials are added into the database.
public void registerAccount(String username, String password, String ipAddress) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager
.getConnection("jdbc:derby:C:\\DB;create=true;upgrade=true");
String query = "INSERT INTO Users (username, password, ip_address) VALUES" + "(?,?,?)";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
preparedStatement.setString(3, ipAddress);
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
e.g.: When a user clicks submit to log in, a method inside the Database class is called:
// Checks if credetials are correct.
public boolean checkLogin(String username, String password) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager
.getConnection("jdbc:derby:C:\\DB;create=true;upgrade=true");
String query = "SELECT username, password from Users WHERE username = ? AND password = ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
String user = resultSet.getString("username");
String pass = resultSet.getString("password");
if (username.equalsIgnoreCase(user)) {
if (password.equals(pass)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return false;
}
I also have a few other methods in the Database class to check if username is not taken when registering, or if an account is already registered on a particular IP, etc. Is this good practice or there are better, more efficient ways of achieving this? Thank you!