Question & Answer: Programmatic access to a MySQL database to add and display records…..

Java

Java

Don't use plagiarized sources. Get Your Custom Essay on
Question & Answer: Programmatic access to a MySQL database to add and display records…..
GET AN ESSAY WRITTEN FOR YOU FROM AS LOW AS $13/PAGE
Order Essay

OBJECTIVES

Programmatic access to a MySQL database to add and display records

PROBLEM: Student Management System

A teacher needs the ability to store and retrieve student data. This includes

·         student name;

·         three test scores;

·         average; and

·         letter grade.

FUNCTIONAL REQUIREMENTS

You can code the GUI by hand or use NetBeans GUI builder interface.

Create a GUI which allows for input and display of student data.

It should include buttons to save a record, display all records.

Create a database and table to store student name and three test scores. (Note that average and grade are calculated by app.)

Student class

Create a Student class to manage the student data. It should have private instance variables of

·         student name; and

·         three test scores.

The class must have the following methods.

·         A default and parameterized constructor

·         Sets/gets for all instance variables

·         A get method to calculate and return the average

·         A get method to calculate and return the letter grade

·         toString to display the name of the student

StudentDB class

Create a StudentDB class that is used to create a connection and interface with the database.

This class should have two methods.

·         getAll—reads data from database, returns data in an arraylist of student objects

·         add—writes a record to the database

GUI class

Insert button will take the info from the GUI (student name and three test scores) and insert a record into the table. Input should be cleared from the textboxes.

Display button will read the data from the database and creates a report in Console window, sample format below.

Name                   Test1     Test2     Test3       Avg       Grade

Bruce Wayne         90         95         98           94.3      A

Clark Kent             65         70         90           75.0      C

Expert Answer

 

————————–StudentFromGUI.java ——————————-

package swing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
@SuppressWarnings(“serial”)
public class StudentFormGUI extends JFrame {
Connection con;
Statement stmt;
ResultSet rst, rstLast;
Object[][] data;
String SHOW = “Show”;
PreparedStatement preStatement, updatePreStmt;
JLabel title, idLabel, nameLabel, testScore1Lbl, testScore2Lbl,
testScore3Lbl;
JTextField idField, nameField, testScore1Field, testScore2Field,
testScore3Field;
JButton submitBtn, displayBtn;
JPanel panel;
JTable table;
DefaultTableModel model;
JScrollPane scrollpane;
public StudentFormGUI() {
super(“Student Record FORM”);
setSize(790, 420);
setLayout(null);
connect();
// Defining Labels
title = new JLabel(“Student Record Form”);
title.setBounds(60, 7, 200, 30);
nameLabel = new JLabel(“Name”);
nameLabel.setBounds(30, 85, 60, 30);
testScore1Lbl = new JLabel(“Test Score1”);
testScore1Lbl.setBounds(10, 120, 200, 30);
testScore2Lbl = new JLabel(“Test Score2”);
testScore2Lbl.setBounds(10, 155, 200, 30);
testScore3Lbl = new JLabel(“Test Score3”);
testScore3Lbl.setBounds(10, 190, 200, 30);

// Defining Name field
nameField = new JTextField();
nameField.setBounds(95, 85, 130, 30);
// Defining Gender Buttons
testScore1Field = new JTextField();
testScore1Field.setBounds(95, 120, 130, 30);
testScore2Field = new JTextField();
testScore2Field.setBounds(95, 155, 130, 30);
testScore3Field = new JTextField();
testScore3Field.setBounds(95, 190, 130, 30);
// fixing all Label,TextField,RadioButton
add(title);
add(nameLabel);
add(testScore1Lbl);
add(testScore2Lbl);
add(testScore3Lbl);
add(nameField);
add(testScore1Field);
add(testScore2Field);
add(testScore3Field);
submitBtn = new JButton(“Submit”);
submitBtn.setBounds(110, 250, 100, 25);
add(submitBtn);
panel = new JPanel();
panel.setLayout(new GridLayout());
panel.setBounds(250, 20, 480, 330);
panel.setBorder(BorderFactory.createDashedBorder(Color.blue));
add(panel);
// Defining Refresh Button
displayBtn = new JButton(“Display”);
displayBtn.setBounds(350, 350, 270, 15);
add(displayBtn);
// Defining Model for table
model = new DefaultTableModel();
// Adding object of DefaultTableModel into JTable
table = new JTable(model);
// Fixing Columns move
table.getTableHeader().setReorderingAllowed(false);
// Defining Column Names on model
model.addColumn(“Name”);
model.addColumn(“Test Score1”);
model.addColumn(“Test Score2”);
model.addColumn(“Test Score3”);
model.addColumn(“Avg”);
model.addColumn(“Grade”);
// Enable Scrolling on table
scrollpane = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
panel.add(scrollpane);
nameField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (nameField.getText().length() >= 15)
e.consume();
}
});
testScore2Field.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (testScore2Field.getText().length() > 50)
e.consume();
}
});
testScore3Field.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((c >= ‘0’) && (c <= ‘9’) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) {
// getToolkit().beep();
e.consume();
}
if (testScore3Field.getText().length() > 9)
e.consume();
}
});
submitBtn.addActionListener(new AbstractAction(SHOW) {
public void actionPerformed(ActionEvent ae) {
try {
if (ae.getSource() == submitBtn) {
if (nameField.getText().equals(“”))
JOptionPane.showMessageDialog(idField,
“Please provide Name_Field”);
else if (testScore1Field.getText().equals(“”))
JOptionPane.showMessageDialog(idField,
“Please provide test Score 1”);
else if (testScore2Field.getText().equals(“”))
JOptionPane.showMessageDialog(idField,
“Please provide test Score 2”);
else if (testScore3Field.equals(“”))
JOptionPane.showMessageDialog(idField,
“Please provide test Score 3”);
else {
// Fetching column values from Database
preStatement.setString(1, nameField.getText());
preStatement.setInt(2,
Integer.parseInt(testScore1Field.getText()));
preStatement.setInt(3,
Integer.parseInt(testScore2Field.getText()));
preStatement.setInt(4,
Integer.parseInt(testScore3Field.getText()));
// Executing MySQL Update Query
int i = preStatement.executeUpdate();
if (i == 1) {
JOptionPane.showMessageDialog(panel,
“Successfully Registered”);
}
displayStudentRecord();
panel.revalidate();
// fields are blank
blankFields();
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
});
displayBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// calling refresh() method
displayStudentRecord();
}
});
table.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent arg0) {
// Getting Selected Row No
int r = table.getSelectedRow();
}
public void mouseReleased(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mouseEntered(MouseEvent arg0) {
}
});
addRows();
// Displaying Frame in Center of the Screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 – this.getSize().width / 2, dim.height
/ 2 – this.getSize().height / 2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
private void displayStudentRecord() {
DefaultTableModel dm = (DefaultTableModel) table.getModel();
dm.getDataVector().removeAllElements();
addRows();
}
private void blankFields() {
nameField.setText(“”);
testScore1Field.setText(“”);
testScore2Field.setText(“”);
testScore3Field.setText(“”);
}
// addRows method
private void addRows() {
try {
Object[] row = null;
rst = stmt.executeQuery(“select * from student”);
while (rst.next()) {
int[] testScore = new int[3];
testScore[0] = rst.getInt(2);
testScore[1] = rst.getInt(3);
testScore[2] = rst.getInt(4);
Student student = new Student(rst.getString(1), testScore);
String str = student.getName() + “,” + testScore[0] + “,”
+ testScore[1] + “,” + testScore[2] + “,”
+ student.getAverage() + “,” + student.getLetterGrade();
row = str.split(“,”);
model.addRow(row);
}
panel.revalidate();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
// Connection with Database
public void connect() {
try {
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/test”, “root”, “1234”);
stmt = con.createStatement();
preStatement = con
.prepareStatement(“insert into student(name,test_score_1,test_score_2,test_score_3) values(?,?,?,?)”);
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
// main() method
public static void main(String[] args) {
new StudentFormGUI();
}
}
——————- End——————————-
Student.java
—————–
package swing;
import java.util.Arrays;
public class Student {
private String name;
private int[] testScores = null;
public Student() {
testScores = new int[3];
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int[] getTestScores() {
return testScores;
}
public void setTestScores(int[] testScores) {
this.testScores = testScores;
}
public Student(String name, int[] testScores) {
super();
this.name = name;
this.testScores = testScores;
}
@Override
public String toString() {
return “Student [name=” + name + “]”;
}
public int getAverage() {
int average = 0;
for (int score : testScores) {
average = average + score;
}
return average / testScores.length;
}
public int getLetterGrade() {
Arrays.sort(testScores);
return testScores[0];
}
}
——————- End———————-
Output
—————

Question & Answer: Programmatic access to a MySQL database to add and display records..... 1

Display

————

1. To see the output, wee need to run the main method of StudentFormGUI.java class.

2. Whole UI devided into two parts

A. Student Form where you can insert the data

B. table part where student data will get displayed.

3. Submit button will insert the record and at the same time table will get reflected with newly added record.

4. Display buttom will show the contents of student table.

5. You can use the below query to create table in database.

CREATE TABLE public.student
(
name character varying(50) NOT NULL,
test_score_1 integer,
test_score_2 integer,
test_score_3 integer
)

Please let me know , if you face any difficulties to run the above program.

Question & Answer: Programmatic access to a MySQL database to add and display records..... 2

You can see the way i have added postgresql jar in my project. please refer the highlighted section. please follow the steps and set the mysql connector jar which you have downloaded.

Still stressed from student homework?
Get quality assistance from academic writers!