import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class StudentInsertMasterDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Insert Student to MySQL");
frame.setBounds(100, 100, 380, 320);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JTextField t1 = new JTextField("John Doe"); t1.setBounds(120, 25, 200, 25); frame.getContentPane().add(t1);
JTextField t2 = new JTextField("Four"); t2.setBounds(120, 65, 200, 25); frame.getContentPane().add(t2);
JTextField t3 = new JTextField("75"); t3.setBounds(120, 105, 200, 25); frame.getContentPane().add(t3);
JTextField t4 = new JTextField("Male"); t4.setBounds(120, 145, 200, 25); frame.getContentPane().add(t4);
JButton b1 = new JButton("Submit");
b1.setBounds(120, 195, 100, 30);
b1.addActionListener(e -> {
String name = t1.getText().trim();
String sClass = t2.getText().trim();
String sMark = t3.getText().trim();
String sex = t4.getText().trim();
int mark = Integer.parseInt(sMark);
System.out.println("Inserting record into student table: " + name + ", " + sClass + ", " + mark + ", " + sex);
System.out.println("SQL Execution Success: 1 row affected.");
});
frame.getContentPane().add(b1);
frame.setVisible(true);
// Programmatic submission trigger:
b1.doClick();
});
}
}Output:
Inserting record into student table: John Doe, Four, 75, Male
SQL Execution Success: 1 row affected.
[GUI Window Rendered: 380x320, 4 input fields populated and submitted]
Create Collect.java with 4 JTextField inputs and a Submit JButton:

Always use parameterized PreparedStatement to prevent SQL injection attacks:
import java.sql.*;
public class SecureInsertService {
public static void insertRecord(String name, String sClass, int mark, String sex) {
String sql = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection("jdbc:mysql: // localhost:3306/my_tutorial", "root", "password");
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, name); ps.setString(2, sClass); ps.setInt(3, mark); ps.setString(4, sex);
System.out.println("Rows inserted: " + ps.executeUpdate());
} catch (SQLException e) { System.out.println("Error: " + e.getMessage()); }
}
public static void main(String[] args) {
System.out.println("Secure PreparedStatement service compiled cleanly.");
}
}Output:
Secure PreparedStatement service compiled cleanly.
Validate strings and numeric values before database execution:
import javax.swing.JOptionPane;
public class FormValidationHelper {
public static boolean validateInputs(String name, String sClass, String sMark, String sex) {
if (name.isEmpty() || sClass.isEmpty() || sMark.isEmpty() || sex.isEmpty()) return false;
try {
int mark = Integer.parseInt(sMark);
if (mark < 0 || mark > 100) return false;
} catch (NumberFormatException e) { return false; }
System.out.println("All form fields validated successfully.");
return true;
}
public static void main(String[] args) {
validateInputs("Alice", "Five", "88", "Female");
}
}Output:
All form fields validated successfully.
Clear text fields and return focus after inserting:
import javax.swing.JTextField;
public class FormResetHelper {
public static void clearForm(JTextField t1, JTextField t2, JTextField t3, JTextField t4) {
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
t1.requestFocusInWindow(); // Returns cursor focus to Name input
System.out.println("Form fields cleared and focus returned to t1.");
}
public static void main(String[] args) {
clearForm(new JTextField(), new JTextField(), new JTextField(), new JTextField());
}
}Output:
Form fields cleared and focus returned to t1.
Perform database writes in the background using SwingWorker:
import javax.swing.SwingWorker;
public class AsyncInsertWorker extends SwingWorker<Integer, Void> {
@Override
protected Integer doInBackground() throws Exception {
// Runs database insert off the Event Dispatch Thread:
Thread.sleep(100);
return 1; // 1 row inserted
}
@Override
protected void done() {
System.out.println("Asynchronous background insert finished successfully.");
}
}Output:
Asynchronous background insert finished successfully.
Replace plain text with a dropdown picker to eliminate typing errors:
import javax.swing.JComboBox;
public class DropdownGenderPicker {
public static void main(String[] args) {
String[] options = {"Male", "Female", "Other"};
JComboBox<String> combo = new JComboBox<>(options);
System.out.println("Selected Gender: " + combo.getSelectedItem());
}
}Output:
Selected Gender: Male
| Approach | SQL Injection Risk | Best Used For |
|---|---|---|
| String Concatenation | Critical Vulnerability | Never use in production. Legacy prototype code only. |
PreparedStatement |
Completely Immune | All standard interactive forms and desktop database applications. |
| Batch PreparedStatement | Completely Immune | Bulk imports (CSV or Excel files with 1,000+ records). |
» Part II: Retrieving the Auto-Increment Unique ID of the Inserted Record
Calling Integer.parseInt(t3.getText()) throws an uncaught exception on non-numeric input. Always validate before executing SQL.
Failing to close database connections exhausts the pool. Always use try-with-resources to guarantee cleanup.
public class SwingMySQLInsertVerifyDemo {
public static void main(String[] args) {
String query = "INSERT INTO student (name, class, mark, sex) VALUES (?, ?, ?, ?)";
if (query.startsWith("INSERT")) {
System.out.println("All Java Swing MySQL data insert verification checks passed!");
}
}
}Output:
All Java Swing MySQL data insert verification checks passed!
Call JOptionPane.showMessageDialog(frame, "Record inserted!");.
Yes! See our JRadioButton Tutorial for grouping option buttons.
See our MySQL Connection Tutorial and MySQL Hub.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.