Let’s create a CRUD application with a MySQL database and user management. This will include connecting to a MySQL database, managing user login, and performing CRUD operations on user data.
Project Setup
- IDE: Use an Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or NetBeans.
- JDK: Ensure you have the Java Development Kit (JDK) installed.
- MySQL: Set up a MySQL server and create a database.
- JDBC Driver: Download and add the MySQL JDBC driver to your project.
MySQL Database Setup
- Create a database named
crud_db
. - Create a table named
users
with the following structure:
CREATE DATABASE crud_db;
USE crud_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(50) NOT NULL,
email VARCHAR(100)
);
Step-by-Step Guide with Code and Comments
1. Create the Main Class
This is the entry point of your application.
package com.crudapp;
public class Main {
public static void main(String[] args) {
// Start the application
LoginFrame loginFrame = new LoginFrame();
loginFrame.setVisible(true);
}
}
2. Create the Database Connection Class
This class handles the connection to the MySQL database.
package com.crudapp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:mysql://localhost:3306/crud_db";
private static final String USER = "root"; // replace with your MySQL username
private static final String PASSWORD = ""; // replace with your MySQL password
// Method to get a connection to the database
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}
Explanation:
URL
,USER
,PASSWORD
: Constants for the database connection details.public static Connection getConnection() throws SQLException
: Method to establish and return a database connection.
3. Create the User Management Class
This class handles user-related operations.
package com.crudapp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserManager {
// Method to add a new user
public static boolean addUser(String username, String password, String email) {
String query = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, username);
stmt.setString(2, password);
stmt.setString(3, email);
int rows = stmt.executeUpdate();
return rows > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
// Method to verify user login
public static boolean verifyUser(String username, String password) {
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
// Method to read all users
public static ResultSet getAllUsers() {
String query = "SELECT * FROM users";
try {
Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(query);
return stmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
// Method to update a user's email
public static boolean updateUserEmail(String username, String newEmail) {
String query = "UPDATE users SET email = ? WHERE username = ?";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, newEmail);
stmt.setString(2, username);
int rows = stmt.executeUpdate();
return rows > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
// Method to delete a user
public static boolean deleteUser(String username) {
String query = "DELETE FROM users WHERE username = ?";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, username);
int rows = stmt.executeUpdate();
return rows > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
Explanation:
addUser
: Adds a new user to the database.verifyUser
: Verifies user login credentials.getAllUsers
: Retrieves all users from the database.updateUserEmail
: Updates the email of a user.deleteUser
: Deletes a user from the database.
4. Create the Login Frame Class
This class handles the user login interface.
package com.crudapp;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame {
private JPanel panel;
private JLabel user
package com.crudapp;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Class for the login frame
public class LoginFrame extends JFrame {
private JPanel panel;
private JLabel userLabel;
private JTextField userTextField;
private JLabel passwordLabel;
private JPasswordField passwordField;
private JButton loginButton;
private JButton registerButton;
private JLabel messageLabel;
// Constructor to set up the login frame
public LoginFrame() {
// Set the title of the frame
setTitle("Login");
// Initialize the components
panel = new JPanel();
userLabel = new JLabel("Username:");
userTextField = new JTextField(20);
passwordLabel = new JLabel("Password:");
passwordField = new JPasswordField(20);
loginButton = new JButton("Login");
registerButton = new JButton("Register");
messageLabel = new JLabel();
// Add components to the panel
panel.add(userLabel);
panel.add(userTextField);
panel.add(passwordLabel);
panel.add(passwordField);
panel.add(loginButton);
panel.add(registerButton);
panel.add(messageLabel);
// Add the panel to the frame
add(panel);
// Set the size of the frame
setSize(300, 200);
// Define what happens when the frame is closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add action listeners for buttons
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
login();
}
});
registerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
register();
}
});
}
// Method to handle login action
private void login() {
String username = userTextField.getText();
String password = new String(passwordField.getPassword());
if (UserManager.verifyUser(username, password)) {
messageLabel.setText("Login successful");
AppFrame appFrame = new AppFrame(username);
appFrame.setVisible(true);
dispose(); // Close the login frame
} else {
messageLabel.setText("Invalid username or password");
}
}
// Method to handle registration action
private void register() {
String username = userTextField.getText();
String password = new String(passwordField.getPassword());
if (UserManager.addUser(username, password, "")) {
messageLabel.setText("User registered successfully");
} else {
messageLabel.setText("User registration failed");
}
}
}
Explanation:
LoginFrame
: A class that creates the login window with components for username, password, and buttons for login and registration.- Action Listeners: Handle the login and registration actions by verifying the user or adding a new user.
5. Create the AppFrame Class
This class sets up the main frame of the GUI after login.
package com.crudapp;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AppFrame extends JFrame {
private JPanel panel;
private JLabel emailLabel;
private JTextField emailTextField;
private JButton updateButton;
private JButton deleteButton;
private JTextArea textArea;
private String username;
// Constructor to set up the frame
public AppFrame(String username) {
this.username = username;
// Set the title of the frame
setTitle("User Management");
// Initialize the components
panel = new JPanel();
emailLabel = new JLabel("New Email:");
emailTextField = new JTextField(20);
updateButton = new JButton("Update Email");
deleteButton = new JButton("Delete User");
textArea = new JTextArea(10, 30);
// Add components to the panel
panel.add(emailLabel);
panel.add(emailTextField);
panel.add(updateButton);
panel.add(deleteButton);
panel.add(new JScrollPane(textArea));
// Add the panel to the frame
add(panel);
// Set the size of the frame
setSize(400, 300);
// Define what happens when the frame is closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Load current user data
loadUserData();
// Add action listeners for buttons
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateEmail();
}
});
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteUser();
}
});
}
// Method to load current user data
private void loadUserData() {
textArea.append("Current Users:\n");
ResultSet rs = UserManager.getAllUsers();
try {
while (rs != null && rs.next()) {
String user = rs.getString("username");
String email = rs.getString("email");
textArea.append(user + " - " + email + "\n");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// Method to update user's email
private void updateEmail() {
String newEmail = emailTextField.getText();
if (UserManager.updateUserEmail(username, newEmail)) {
textArea.append("Updated email to: " + newEmail + "\n");
emailTextField.setText("");
} else {
textArea.append("Failed to update email\n");
}
}
// Method to delete user
private void deleteUser() {
if (UserManager.deleteUser(username)) {
textArea.append("Deleted user: " + username + "\n");
dispose(); // Close the app frame
} else {
textArea.append("Failed to delete user\n");
}
}
}
Explanation:
AppFrame
: A class that creates the main application window for user management after login.- Constructor: Sets up the GUI components and loads current user data.
loadUserData
: Fetches and displays all users from the database.updateEmail
: Updates the email address of the logged-in user.deleteUser
: Deletes the logged-in user from the database.
Running the Application
- Run the
Main
class. - The login window will appear. Use it to log in or register a new user.
- Upon successful login, the main application window will appear, allowing you to manage user data.
This guide provides a simple CRUD application with MySQL integration and user management, along with detailed explanations and comments to help beginners understand each step and component.
Welcome to DevTechTutor.com, your ultimate resource for mastering web development and technology! Whether you're a beginner eager to dive into coding or an experienced developer looking to sharpen your skills, DevTechTutor.com is here to guide you every step of the way. Our mission is to make learning web development accessible, engaging, and effective.