By GokiSoft.com| 19:50 15/08/2022|
Java Advanced

[Source Code] [Examination] Kiểm tra 60 phút - Đề 3 - C2108L

[Examination] Kiểm tra 60 phút - Đề 3



Nội dung kiến thức:
	- OOP
	- Java II
		- Exception
		- Vector, ArrayList, HashMap
		- Xử lý File
			- FileInputStream/FileOutStream
			- FileReader/BufferedReader & FileWriter/BufferWriter
			- ObjectFileInputStream/ObjectFileOutputStream
		- Xử lý nhập dữ liệu
			- Scanner
			- ...
		- Thread
			- 2 -> 3 Threads
			- synchronized: 2 Threads
		- Database
			- CRUD (Thêm/sửa/xoá/danh sách)
		- Java Swing
======================================================================
#1164

B1) Phan tich database
create database C2108L

create table students (
	id int primary key auto_increment,
	rollno varchar(20) unique,
	fullname varchar(50) not null,
	gender varchar(20),
	email varchar(150),
	address varchar(200)
)

B2) TAO DU AN
B3) Add thu vien -> jdbc mysql driver
B4) Ket noi CSDL -> Generate Entity
B5) Thiet ket chuc nang




#StudentFrame.java


/*
 * 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 com.gokisoft;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Diep.Tran
 */
public class StudentFrame extends javax.swing.JFrame {
    Student std = null;
    DefaultTableModel tableModel;
    
    List<Student> dataList;

    /**
     * Creates new form StudentFrame
     */
    public StudentFrame() {
        initComponents();
        
        tableModel = (DefaultTableModel) tblStudent.getModel();
        dataList = new ArrayList<>();
        
        showDataOnTable();
    }
    
    private void showDataOnTable() {
        dataList = StudentDAO.getDataList();
        
        tableModel.setRowCount(0);
        
        for (Student student : dataList) {
            tableModel.addRow(new Object[] {
                tableModel.getRowCount() + 1,
                student.getFullname(),
                student.getGender(),
                student.getEmail(),
                student.getAddress()
            });
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtFullname = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtRollno = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtAddress = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        cbGender = new javax.swing.JComboBox<>();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblStudent = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Full Name:");

        jLabel2.setText("RollNo:");

        jLabel3.setText("Email:");

        jLabel4.setText("Gender:");

        jLabel5.setText("Address:");

        jButton1.setText("Update");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Reset");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Search");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        cbGender.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Male", "Female" }));

        tblStudent.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "NO", "Full Name", "Gender", "Email", "Address"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblStudent);
        if (tblStudent.getColumnModel().getColumnCount() > 0) {
            tblStudent.getColumnModel().getColumn(0).setResizable(false);
            tblStudent.getColumnModel().getColumn(1).setResizable(false);
            tblStudent.getColumnModel().getColumn(2).setResizable(false);
            tblStudent.getColumnModel().getColumn(3).setResizable(false);
            tblStudent.getColumnModel().getColumn(4).setResizable(false);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4))
                                .addGap(67, 67, 67)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtRollno, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtFullname, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(38, 38, 38)
                                        .addComponent(jButton3))
                                    .addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(76, 76, 76)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jButton1)
                                        .addGap(29, 29, 29)
                                        .addComponent(jButton2))
                                    .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 715, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.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)
                    .addComponent(jButton3))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtRollno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(50, 50, 50)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(41, 41, 41)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        txtFullname.setText("");
        txtAddress.setText("");
        txtRollno.setText("");
        txtEmail.setText("");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        String rollno = txtRollno.getText();
        if(rollno.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Input rollno to search!!!");
            return;
        }
        std = StudentDAO.findByRollno(rollno);
        if(std == null) {
            JOptionPane.showMessageDialog(rootPane, "Search not found!");
            return;
        }
        
        txtFullname.setText(std.getFullname());
        txtEmail.setText(std.getEmail());
        txtAddress.setText(std.getAddress());
        cbGender.setSelectedItem(std.getGender());
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if(std == null) {
            JOptionPane.showMessageDialog(rootPane, "not update!");
            return;
        }
        
        std.setFullname(txtFullname.getText());
        std.setEmail(txtEmail.getText());
        std.setAddress(txtAddress.getText());
        std.setRollno(txtRollno.getText());
        std.setGender(cbGender.getSelectedItem().toString());
        
        StudentDAO.update(std);
        
        jButton2ActionPerformed(null);
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @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//GEN-BEGIN:variables
    private javax.swing.JComboBox<String> cbGender;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    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.JScrollPane jScrollPane1;
    private javax.swing.JTable tblStudent;
    private javax.swing.JTextField txtAddress;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtFullname;
    private javax.swing.JTextField txtRollno;
    // End of variables declaration//GEN-END:variables
}


#StudentFrame.form


<?xml version="1.0" encoding="UTF-8" ?>

<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
  <Properties>
    <Property name="defaultCloseOperation" type="int" value="3"/>
  </Properties>
  <SyntheticProperties>
    <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
    <SyntheticProperty name="generateCenter" type="boolean" value="false"/>
  </SyntheticProperties>
  <AuxValues>
    <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
    <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
  </AuxValues>

  <Layout>
    <DimensionLayout dim="0">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" attributes="0">
              <Group type="103" groupAlignment="0" attributes="0">
                  <Group type="102" attributes="0">
                      <EmptySpace min="-2" pref="65" max="-2" attributes="0"/>
                      <Group type="103" groupAlignment="0" attributes="0">
                          <Group type="102" attributes="0">
                              <Group type="103" groupAlignment="0" attributes="0">
                                  <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
                                  <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
                                  <Component id="jLabel3" alignment="0" min="-2" max="-2" attributes="0"/>
                                  <Component id="jLabel4" alignment="0" min="-2" max="-2" attributes="0"/>
                              </Group>
                              <EmptySpace min="-2" pref="67" max="-2" attributes="0"/>
                              <Group type="103" groupAlignment="0" attributes="0">
                                  <Component id="txtEmail" min="-2" pref="401" max="-2" attributes="0"/>
                                  <Component id="txtRollno" min="-2" pref="401" max="-2" attributes="0"/>
                                  <Group type="102" attributes="0">
                                      <Component id="txtFullname" min="-2" pref="401" max="-2" attributes="0"/>
                                      <EmptySpace min="-2" pref="38" max="-2" attributes="0"/>
                                      <Component id="jButton3" min="-2" max="-2" attributes="0"/>
                                  </Group>
                                  <Component id="cbGender" min="-2" max="-2" attributes="0"/>
                              </Group>
                          </Group>
                          <Group type="102" alignment="0" attributes="0">
                              <Component id="jLabel5" min="-2" max="-2" attributes="0"/>
                              <EmptySpace min="-2" pref="76" max="-2" attributes="0"/>
                              <Group type="103" groupAlignment="0" attributes="0">
                                  <Group type="102" attributes="0">
                                      <Component id="jButton1" min="-2" max="-2" attributes="0"/>
                                      <EmptySpace min="-2" pref="29" max="-2" attributes="0"/>
                                      <Component id="jButton2" min="-2" max="-2" attributes="0"/>
                                  </Group>
                                  <Component id="txtAddress" min="-2" pref="401" max="-2" attributes="0"/>
                              </Group>
                          </Group>
                      </Group>
                  </Group>
                  <Group type="102" alignment="0" attributes="0">
                      <EmptySpace min="-2" pref="16" max="-2" attributes="0"/>
                      <Component id="jScrollPane1" min="-2" pref="715" max="-2" attributes="0"/>
                  </Group>
              </Group>
              <EmptySpace pref="21" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
    <DimensionLayout dim="1">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" alignment="0" attributes="0">
              <EmptySpace min="-2" pref="49" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="txtFullname" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="jButton3" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace min="-2" pref="32" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="txtRollno" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace min="-2" pref="33" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="txtEmail" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace min="-2" pref="39" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel4" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="cbGender" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace min="-2" pref="41" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel5" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="txtAddress" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace min="-2" pref="50" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jButton1" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="jButton2" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace min="-2" pref="41" max="-2" attributes="0"/>
              <Component id="jScrollPane1" min="-2" pref="260" max="-2" attributes="0"/>
              <EmptySpace pref="14" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Component class="javax.swing.JLabel" name="jLabel1">
      <Properties>
        <Property name="text" type="java.lang.String" value="Full Name:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JTextField" name="txtFullname">
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel2">
      <Properties>
        <Property name="text" type="java.lang.String" value="RollNo:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JTextField" name="txtRollno">
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel3">
      <Properties>
        <Property name="text" type="java.lang.String" value="Email:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JTextField" name="txtEmail">
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel4">
      <Properties>
        <Property name="text" type="java.lang.String" value="Gender:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel5">
      <Properties>
        <Property name="text" type="java.lang.String" value="Address:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JTextField" name="txtAddress">
    </Component>
    <Component class="javax.swing.JButton" name="jButton1">
      <Properties>
        <Property name="text" type="java.lang.String" value="Update"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JButton" name="jButton2">
      <Properties>
        <Property name="text" type="java.lang.String" value="Reset"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton2ActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JButton" name="jButton3">
      <Properties>
        <Property name="text" type="java.lang.String" value="Search"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton3ActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JComboBox" name="cbGender">
      <Properties>
        <Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
          <StringArray count="2">
            <StringItem index="0" value="Male"/>
            <StringItem index="1" value="Female"/>
          </StringArray>
        </Property>
      </Properties>
      <AuxValues>
        <AuxValue name="JavaCodeGenerator_TypeParameters" type="java.lang.String" value="&lt;String&gt;"/>
      </AuxValues>
    </Component>
    <Container class="javax.swing.JScrollPane" name="jScrollPane1">
      <AuxValues>
        <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
      </AuxValues>

      <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
      <SubComponents>
        <Component class="javax.swing.JTable" name="tblStudent">
          <Properties>
            <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
              <Table columnCount="5" rowCount="0">
                <Column editable="false" title="NO" type="java.lang.Object"/>
                <Column editable="false" title="Full Name" type="java.lang.Object"/>
                <Column editable="false" title="Gender" type="java.lang.Object"/>
                <Column editable="false" title="Email" type="java.lang.Object"/>
                <Column editable="false" title="Address" type="java.lang.Object"/>
              </Table>
            </Property>
            <Property name="columnModel" type="javax.swing.table.TableColumnModel" editor="org.netbeans.modules.form.editors2.TableColumnModelEditor">
              <TableColumnModel selectionModel="0">
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
              </TableColumnModel>
            </Property>
            <Property name="tableHeader" type="javax.swing.table.JTableHeader" editor="org.netbeans.modules.form.editors2.JTableHeaderEditor">
              <TableHeader reorderingAllowed="true" resizingAllowed="true"/>
            </Property>
          </Properties>
        </Component>
      </SubComponents>
    </Container>
  </SubComponents>
</Form>


#StudentDAO.java


/*
 * 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 com.gokisoft;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class StudentDAO {
    static Connection connection;
    static PreparedStatement statement;
    
    static void openConnection() {
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/C2108L", "root", "");
        } catch (SQLException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    static void closeConnection() {
        if(statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public static List<Student> getDataList() {
        List<Student> dataList = new ArrayList<>();
        
        openConnection();
        
        String sql = "select * from students";
        try {
            statement = connection.prepareStatement(sql);
            
            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next()) {
                Student std = new Student(
                        resultSet.getInt("id"), 
                        resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("email"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("address")
                );
                dataList.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
        
        return dataList;
    }
    
    public static Student findByRollno(String rollno) {
        Student std = null;
        
        openConnection();
        
        String sql = "select * from students where rollno = ?";
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, rollno);
            
            ResultSet resultSet = statement.executeQuery();
            
            if(resultSet.next()) {
                std = new Student(
                        resultSet.getInt("id"), 
                        resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("email"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("address")
                );
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
        
        return std;
    }
    
    public static Student findById(int id) {
        Student std = null;
        
        openConnection();
        
        String sql = "select * from students where id = ?";
        try {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, id);
            
            ResultSet resultSet = statement.executeQuery();
            
            if(resultSet.next()) {
                std = new Student(
                        resultSet.getInt("id"), 
                        resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("email"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("address")
                );
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
        
        return std;
    }
    
    public static void insert(Student std) {
        openConnection();
        
        String sql = "insert into students(rollno, fullname, email, gender, address) values (?, ?, ?, ?, ?)";
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, std.getRollno());
            statement.setString(2, std.getFullname());
            statement.setString(3, std.getEmail());
            statement.setString(4, std.getGender());
            statement.setString(5, std.getAddress());
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
    }
    
    public static void update(Student std) {
        openConnection();
        
        String sql = "update students set rollno = ?, fullname = ?, email = ?, gender = ?, address = ? where id = ?";
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, std.getRollno());
            statement.setString(2, std.getFullname());
            statement.setString(3, std.getEmail());
            statement.setString(4, std.getGender());
            statement.setString(5, std.getAddress());
            statement.setInt(6, std.getId());
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
    }
    
    public static void delete(int id) {
        openConnection();
        
        String sql = "delete from students where id = ?";
        try {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, id);
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
    }
}


#Student.java


/*
 * 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 com.gokisoft;

/**
 *
 * @author Diep.Tran
 */
public class Student {
    int id;
    String rollno, fullname, email, gender, address;

    public Student() {
    }

    public Student(int id, String rollno, String fullname, String email, String gender, String address) {
        this.id = id;
        this.rollno = rollno;
        this.fullname = fullname;
        this.email = email;
        this.gender = gender;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getRollno() {
        return rollno;
    }

    public void setRollno(String rollno) {
        this.rollno = rollno;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" + "id=" + id + ", rollno=" + rollno + ", fullname=" + fullname + ", email=" + email + ", gender=" + gender + ", address=" + address + '}';
    }
    
    
}


#pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gokisoft</groupId>
    <artifactId>BT1164</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

    </dependencies>
</project>


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)