Inserting Data into MySQL Table Using JFrame

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]

1. Designing the Input Form in Eclipse WindowBuilder 🔝

Create Collect.java with 4 JTextField inputs and a Submit JButton:

Swing JFrame to enter data

2. Database Security: PreparedStatement vs String Concatenation 🔝

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.

3. Defensive Input Validation Before Database Execution 🔝

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.

4. Resetting Form Fields and Returning Keyboard Focus 🔝

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.

5. Background Database Insertion with SwingWorker 🔝

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

7. Comparison: Java Database Insertion Approaches 🔝

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

8. Common Developer Pitfalls & Traps 🔝

NumberFormatException on Unvalidated Marks

Calling Integer.parseInt(t3.getText()) throws an uncaught exception on non-numeric input. Always validate before executing SQL.

Unclosed Database Connections and Statement Leaks

Failing to close database connections exhausts the pool. Always use try-with-resources to guarantee cleanup.

9. Complete Compilable Java Program 🔝

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!

10. Frequently Asked Questions (FAQ) 🔝

How do I get the generated auto-increment ID after inserting?

See Retrieving Auto-Increment ID with getGeneratedKeys.

How do I show a popup notification after a successful insert?

Call JOptionPane.showMessageDialog(frame, "Record inserted!");.

Can I use JRadioButton or JCheckBox instead of text fields for Sex?

Yes! See our JRadioButton Tutorial for grouping option buttons.

How do I display the inserted records in a table on another window?

See Displaying MySQL Records in JTable.

Where can I read more about MySQL connections in Java?

See our MySQL Connection Tutorial and MySQL Hub.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer