Questions and Answers
Questions and Answers
Question:
Design a database application with the information below
Create a form (registration form) in Java with the following fields: Reg number, Surname,
First name, middle name, matric number, dob, picture, and course.
Design a database with MySQL with the fields stated above, hence or otherwise connect the
frontend to the backend using the JDBC driver.
NB: you are to fill the respective field with information and the information entered should
be displayed on the MySQL Database.
Answer:
To create the required database application with the registration form in Java and connect it
to a MySQL database using JDBC, we will break the task into several parts:
First, we need to create a MySQL database and a table to store the registration data.
USE registration_db;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.io.*;
// Initialize components
txtRegNumber = new JTextField();
txtSurname = new JTextField();
txtFirstName = new JTextField();
txtMiddleName = new JTextField();
txtMatricNumber = new JTextField();
txtCourse = new JTextField();
txtDob = new JDateChooser();
lblPicture = new JLabel("No picture selected");
btnUpload = new JButton("Upload Picture");
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get user inputs
String regNumber = txtRegNumber.getText();
String surname = txtSurname.getText();
String firstName = txtFirstName.getText();
String middleName = txtMiddleName.getText();
String matricNumber = txtMatricNumber.getText();
java.util.Date dob = txtDob.getDate();
String course = txtCourse.getText();
Date sqlDob = new java.sql.Date(dob.getTime());
try {
Connection connection = DriverManager.getConnection(dbURL, dbUsername,
dbPassword);
String query = "INSERT INTO student_registration (reg_number, surname,
first_name, middle_name, matric_number, dob, picture, course) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, regNumber);
pst.setString(2, surname);
pst.setString(3, firstName);
pst.setString(4, middleName);
pst.setString(5, matricNumber);
pst.setDate(6, sqlDob);
pst.setBytes(7, pictureData);
pst.setString(8, course);
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Database connection failed!");
}
}
});
}
// Main method to run the registration form
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new RegistrationForm().setVisible(true);
}
});
}
}