Sử dụng lệnh DELETE trong Java JDBC.
Cú pháp SQL:
DELETE FROM tên_bảng WHERE điều_kiện;
Ví dụ Java xóa bản ghi id=101:
import java.sql.*;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class JavaDeleteDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost/business", "Manish", "123456");
stmt = (Statement) conn.createStatement();
String sql = "DELETE FROM DeleteTableDemo WHERE id=101";
stmt.executeUpdate(sql);
System.out.println("Xóa thành công");
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
Sau khi chạy, bản ghi id=101 bị xóa.