UserManagementLab
UserManagementLab
Objective
By the end of this lab, you will:
1. Create a `DBAccess` class to manage database connections and operations.
2. Refactor the `Users` class to use `DBAccess` for database interactions.
3. Integrate the database with a forms application for user registration and login.
3. Record your database URL, username, and password. These will be used to connect your
application to the database.
private DBAccess() {
String jdbcURL = "jdbc:h2:~/mydatabase";
String username = "sa";
String password = "";
try {
connection = DriverManager.getConnection(jdbcURL,
username, password);
System.out.println("Database connection
established.");
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("Failed to connect to the
database");
}
}
3. Set the placeholders (`?`) using values from the `User` object:
- `user.getFirstName()` + " " + `user.getLastName()` for the username.
- `user.getEmail()` for the email.
- `user.getPassword()` for the password.
4. Handle exceptions to check for duplicate email errors (unique constraint violations).
4. Check if the result is `0` (email is unique) or greater than `0` (email already exists). Return
`true` for unique emails and `false` otherwise.
**Hint**: Here's how you can use `ResultSet` to get the count:
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
int count = rs.getInt(1);
return count == 0;
}
2. Ensure that `Users` still handles password validation (e.g., checking for strength).
3. Test this method by creating a `Users` object and calling `addUser` with various `User` objects.
Step 6: Integrate with the Forms Application
**Goal**: Connect the database logic with your forms for user registration and login.
1. In your registration form:
- Collect user input for first name, last name, email, and password.
- Create a `User` object with the input data.
- Call the `addUser()` method from the `Users` class to register the user.
3. Show messages on the form based on success or failure (e.g., 'Registration successful!' or
'Invalid email or password').