How to Insert Records
In database management, inserting records refers to the process of adding new data entries to a database table using the SQL INSERT statement. Each inserted record corresponds to a new row containing values for one or more columns.
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;
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 btnInsertActionPerformed(java.awt.event.ActionEvent evt) {
String id = txtID.getText().trim();
String name = txtName.getText().trim();
String gender = txtGender.getText().trim();
String address = txtAddress.getText().trim();
String phone = txtPhone.getText().trim();
// ✅ Check required fields
if (id.isEmpty() || name.isEmpty() || gender.isEmpty() || address.isEmpty() || phone.isEmpty()) {
JOptionPane.showMessageDialog(this, "All fields are required!", "Error", JOptionPane.ERROR_MESSAGE);
return; // stop here, don’t insert
}
try {
pst = conn.prepareStatement("INSERT INTO students(id, name, gender, address, phone) VALUES(?,?,?,?,?)");
pst.setInt(1, Integer.parseInt(id));
pst.setString(2, name);
pst.setString(3, gender);
pst.setString(4, address);
pst.setString(5, phone);
int k = pst.executeUpdate();
if (k == 1) {
JOptionPane.showMessageDialog(this, "Record Added Successfully!");
// Clear fields after insert
txtID.setText("");
txtName.setText("");
txtGender.setText("");
txtAddress.setText("");
txtPhone.setText("");
txtID.requestFocus();
} else {
JOptionPane.showMessageDialog(this, " Failed to Insert Record!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Result:
Watch the video:
.jpg)
