🛢️ MySQL Connection & CRUD Operations in Java

🛢️ MySQL Connection & CRUD Operations in Java

In this guide, you will learn how to connect Java applications to a MySQL database and perform basic CRUD (Create, Read, Update, Delete) operations using JDBC (Java Database Connectivity).

🔌 1. Setting up MySQL Connector

First, download the MySQL Connector/J (JDBC driver) and add the JAR file to your project’s build path or dependencies.

📡 2. Connecting to MySQL Database

  import java.sql.Connection; import java.sql.DriverManager; 
import java.sql.SQLException;
public class DBConnection {
private static final String URL = "jdbc:mysql://localhost:3306/testdb";
private static final String USER = "root";
private static final String PASSWORD = "your_password";

public static Connection getConnection() {
    try {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    } catch (SQLException e) {
        System.out.println("Connection Failed!");
        e.printStackTrace();
        return null;
    }
}

public static void main(String[] args) {
    Connection conn = getConnection();
    if (conn != null) {
        System.out.println("Connected to the database successfully!");
    }
}
}

➕ 3. Create Operation (Insert Data)

  import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
public class CreateRecord {
public static void main(String[] args) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
    try (Connection conn = DBConnection.getConnection();
         PreparedStatement stmt = conn.prepareStatement(sql)) {

        stmt.setString(1, "John Doe");
        stmt.setString(2, "john.doe@example.com");

        int rowsInserted = stmt.executeUpdate();
        if (rowsInserted > 0) {
            System.out.println("A new user was inserted successfully!");
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

📖 4. Read Operation (Select Data)

  import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
public class ReadRecords {
public static void main(String[] args) {
String sql = "SELECT id, name, email FROM users";
    try (Connection conn = DBConnection.getConnection();
         PreparedStatement stmt = conn.prepareStatement(sql);
         ResultSet rs = stmt.executeQuery()) {

        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String email = rs.getString("email");

            System.out.println(id + " | " + name + " | " + email);
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

✏️ 5. Update Operation

  import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
public class UpdateRecord {
public static void main(String[] args) {
String sql = "UPDATE users SET email = ? WHERE name = ?";
    try (Connection conn = DBConnection.getConnection();
         PreparedStatement stmt = conn.prepareStatement(sql)) {

        stmt.setString(1, "new.email@example.com");
        stmt.setString(2, "John Doe");

        int rowsUpdated = stmt.executeUpdate();
        if (rowsUpdated > 0) {
            System.out.println("User's email updated successfully!");
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

🗑️ 6. Delete Operation

  import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
public class DeleteRecord {
public static void main(String[] args) {
String sql = "DELETE FROM users WHERE name = ?";
    try (Connection conn = DBConnection.getConnection();
         PreparedStatement stmt = conn.prepareStatement(sql)) {

        stmt.setString(1, "John Doe");

        int rowsDeleted = stmt.executeUpdate();
        if (rowsDeleted > 0) {
            System.out.println("User deleted successfully!");
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

✅ Conclusion

Using JDBC, Java can easily connect to a MySQL database and perform CRUD operations. Always remember to close your resources properly (or use try-with-resources), and handle SQL exceptions for a robust application.

Comments

Popular posts from this blog

Remove (Clear) and remove Selected element

JSpinner