How to Delete Records
Deleting Records in a database means removing existing rows from a table by using the SQL DELETE statements.
Example: Deleting Records in Java
Source Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JOptionPane;
public class Insertstudent extends javax.swing.JFrame{
Connection conn;
PreparedStatement pst;
ResultSet rs;
public Insertstudents() {
initComponents();
connect();
}
public void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost/studentdb?useSSL=false&serverTimezone=Asia/Phnom_Penh";
String user = "root";
String pass = "root";
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
String id = txtID.getText().trim();
if (id.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please enter ID to delete");
return;
}
int confirm = JOptionPane.showConfirmDialog(this,
"Are you sure you want to delete this record?",
"Confirm Delete", JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
try {
PreparedStatement pst = conn.prepareStatement("DELETE FROM students WHERE id=?");
pst.setInt(1, Integer.parseInt(id));
int k = pst.executeUpdate();
if (k == 1) {
JOptionPane.showMessageDialog(this, "Record Deleted Successfully!");
} else {
JOptionPane.showMessageDialog(this, "Record Not Found!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Result:
Watch the video:
.png)
