JDBC 7: Adding Students using a GUI

Create DBase.addStudent(Student student) Method

public static void addStudent(Student student) {

    makeConnection();
    try {
    PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
    prep.setString(1, student.getForename());
    prep.setString(2, student.getSurname());
    prep.setString(3, student.getGender());
    prep.setString(4, student.getForm());

    prep.executeUpdate();

    con.close();

    } catch (SQLException ex) {
    System.err.println(ex);
    }

}

Create GUIAddStudent Class

The following code will display the simple GUI shown

package dbase2016;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

/**
 *
 * @author ajb
 */
public class GUIAddStudent extends JFrame implements ActionListener{

    JLabel lblForename = new JLabel("Forename");
    JLabel lblSurname = new JLabel("Surname");
    JLabel lblGender = new JLabel("Gender");
    JLabel lblForm = new JLabel("Form");

    JTextField txtForename = new JTextField("");
    JTextField txtSurname = new JTextField("");
    JTextField txtGender = new JTextField("");
    JTextField txtForm = new JTextField("");

    JButton OK = new JButton("OK");


    GUIAddStudent()
    {
    Container vert = Box.createVerticalBox();
    vert.add(lblForename);
    vert.add(txtForename);
    vert.add(lblSurname);
    vert.add(txtSurname);
    vert.add(lblGender);
    vert.add(txtGender);
    vert.add(lblForm);
    vert.add(txtForm);

    vert.add(OK);

    OK.addActionListener(this);
    add(vert);

    this.setSize(300,250);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    }

    @Override
    public void actionPerformed(ActionEvent ae) {
    Student student = new Student();
    student.setForename(txtForename.getText());
    student.setSurname(txtSurname.getText());
    student.setGender(txtGender.getText());
    student.setForm(txtForm.getText());

    DBase.addStudent(student);

    GUIDisplayStudents  displayPupils = new GUIDisplayStudents(DBase.getPupils());
    displayPupils.setVisible(true);
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.