create table student (
id int primary key auto_increment,
fullname varchar(50) not null,
gender varchar(15),
age int,
email varchar(150),
phone_number varchar(15)
)
public class Student {
int id;
String fullname, gender, email, phoneNumber;
int age;
public Student() {
}
public Student(int id, String fullname, String gender, String email, String phoneNumber, int age) {
this.id = id;
this.fullname = fullname;
this.gender = gender;
this.email = email;
this.phoneNumber = phoneNumber;
this.age = age;
}
public Student(String fullname, String gender, String email, String phoneNumber, int age) {
this.fullname = fullname;
this.gender = gender;
this.email = email;
this.phoneNumber = phoneNumber;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StudentModify {
public static List<Student> findAll() {
List<Student> studentList = new ArrayList<>();
Connection connection = null;
Statement statement = null;
try {
//lay tat ca danh sach sinh vien
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_management", "root", "");
//query
String sql = "select * from student";
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
Student std = new Student(resultSet.getInt("id"),
resultSet.getString("fullname"), resultSet.getString("gender"),
resultSet.getString("email"), resultSet.getString("phone_number"),
resultSet.getInt("age"));
studentList.add(std);
}
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//ket thuc.
return studentList;
}
public static void insert(Student std) {
Connection connection = null;
PreparedStatement statement = null;
try {
//lay tat ca danh sach sinh vien
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_management", "root", "");
//query
String sql = "insert into student(fullname, gender, age, email, phone_number) values(?, ?, ?, ?, ?)";
statement = connection.prepareCall(sql);
statement.setString(1, std.getFullname());
statement.setString(2, std.getGender());
statement.setInt(3, std.getAge());
statement.setString(4, std.getEmail());
statement.setString(5, std.getPhoneNumber());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//ket thuc.
}
public static void update(Student std) {
Connection connection = null;
PreparedStatement statement = null;
try {
//lay tat ca danh sach sinh vien
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_management", "root", "");
//query
String sql = "update student set fullname=?,gender=?,age=?,email=?,phone_number=? where id = ?";
statement = connection.prepareCall(sql);
statement.setString(1, std.getFullname());
statement.setString(2, std.getGender());
statement.setInt(3, std.getAge());
statement.setString(4, std.getEmail());
statement.setString(5, std.getPhoneNumber());
statement.setInt(6, std.getId());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//ket thuc.
}
public static void delete(int id) {
Connection connection = null;
PreparedStatement statement = null;
try {
//lay tat ca danh sach sinh vien
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_management", "root", "");
//query
String sql = "delete from student where id = ?";
statement = connection.prepareCall(sql);
statement.setInt(1, id);
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//ket thuc.
}
public static List<Student> findByFullname(String fullname) {
List<Student> studentList = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
try {
//lay tat ca danh sach sinh vien
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_management", "root", "");
//query
String sql = "select * from student where fullname like ?";
statement = connection.prepareCall(sql);
statement.setString(1, "%"+fullname+"%");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Student std = new Student(resultSet.getInt("id"),
resultSet.getString("fullname"), resultSet.getString("gender"),
resultSet.getString("email"), resultSet.getString("phone_number"),
resultSet.getInt("age"));
studentList.add(std);
}
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//ket thuc.
return studentList;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lession8;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class StudentFrame extends javax.swing.JFrame {
DefaultTableModel tableModel;
List<Student> studentList = new ArrayList<>();
public StudentFrame() {
initComponents();
tableModel = (DefaultTableModel) tblStudent.getModel();
showStudent();
}
private void showStudent() {
studentList = StudentModify.findAll();
tableModel.setRowCount(0);
studentList.forEach((student) -> {
tableModel.addRow(new Object[] {tableModel.getRowCount() + 1, student.getFullname(),
student.getGender(), student.getEmail(), student.getPhoneNumber()});
});
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtFullname = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
cbGender = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
txtAge = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtEmail = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtPhoneNumber = new javax.swing.JTextField();
btnSave = new javax.swing.JButton();
btnReset = new javax.swing.JButton();
btnDelete = new javax.swing.JButton();
btnFind = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblStudent = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Student Manager");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input Student's Detail Information"));
jLabel1.setText("Full Name:");
jLabel2.setText("Gender: ");
cbGender.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Male", "Female" }));
jLabel3.setText("Age:");
jLabel4.setText("Email:");
jLabel5.setText("Phone Number:");
btnSave.setText("Save");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnReset.setText("Reset");
btnReset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnResetActionPerformed(evt);
}
});
btnDelete.setText("Delete");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
btnFind.setText("Find");
btnFind.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(77, 77, 77)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtFullname)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(116, 116, 116)
.addComponent(txtAge, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel4))
.addGap(48, 48, 48)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtEmail)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnSave)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnReset)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDelete)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnFind))
.addComponent(txtPhoneNumber))))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtFullname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtAge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtPhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSave)
.addComponent(btnReset)
.addComponent(btnDelete)
.addComponent(btnFind))
.addContainerGap(19, Short.MAX_VALUE))
);
tblStudent.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Full Name", "Gender", "Email", "Address"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, true, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tblStudent);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtFullname.setText("");
cbGender.setSelectedIndex(0);
txtAge.setText("");
txtEmail.setText("");
txtPhoneNumber.setText("");
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String fullname = txtFullname.getText();
String gender = cbGender.getSelectedItem().toString();
int age = Integer.parseInt(txtAge.getText());
String email = txtEmail.getText();
String phoneNumber = txtPhoneNumber.getText();
Student std = new Student(fullname, gender, email, phoneNumber, age);
StudentModify.insert(std);
showStudent();
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int selectedIndex = tblStudent.getSelectedRow();
if(selectedIndex >= 0) {
Student std = studentList.get(selectedIndex);
int option = JOptionPane.showConfirmDialog(this, "Do you want to delete this item?");
System.out.println("option : " + option);
if(option == 0) {
StudentModify.delete(std.getId());
showStudent();
}
}
}
private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String input = JOptionPane.showInputDialog(this, "Enter full name to search");
if(input != null && input.length() > 0) {
studentList = StudentModify.findByFullname(input);
tableModel.setRowCount(0);
studentList.forEach((student) -> {
tableModel.addRow(new Object[] {tableModel.getRowCount() + 1, student.getFullname(),
student.getGender(), student.getEmail(), student.getPhoneNumber()});
});
} else {
showStudent();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StudentFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnFind;
private javax.swing.JButton btnReset;
private javax.swing.JButton btnSave;
private javax.swing.JComboBox<String> cbGender;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblStudent;
private javax.swing.JTextField txtAge;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtFullname;
private javax.swing.JTextField txtPhoneNumber;
// End of variables declaration
}