By GokiSoft.com| 20:26 14/04/2023|
Java Advanced

Quản lý sinh viên + XML + JSON + MySQL bằng Java

Thiết kế CSDL đặt tên là : quanlysinhvien

Tạo 1 bảng students gồm các thuộc tính : rollno, fullname, gender, email, address

Nhập vào bảng trên ít nhất 3 sinh viên bất kỳ.

Thiết kế phần mềm có giao diện như sau

Khi người dùng nhấn vào button search thực hiện task vụ sau

- Nếu RollNo : để trống thì hiển thị message yêu cầu nhập rollno cần tìm kiếm

- Nếu RollNo : khác rỗng -> thực hiện tìm kiếm sinh viên trong csdl và hiển thị ra các trường trong form

Khi người dùng click reset thì xoá toàn bộ dữ liệu sv trong form

Khi người dùng click vào update thì cập nhật dữ liệu trong CSDL và xoá tất cả các dữ liệu trong form.

- Thiết kế thêm chức năng Import từ XML và JSON => khi click vào chức năng này thực hiện đọc dữ liệu từ file XML hoặc JSON và insert vào CSDL. TH rollNo chưa có thì thêm mới, nếu có rồi thi update

- Thiết kế chức năng Export XML/JSON => Khi click vào chức năng này => show lên dialog cho phép nhập searchValue => thực hiện export sinh viên có tên hoặc rollNo theo dữ liệu searchValue (sử dụng mệ đề like trong câu query)

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

5

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

GokiSoft.com [Teacher]
GokiSoft.com

2021-09-21 03:30:35



B1. Tao database

create table students (
	id int primary key auto_increment,
	fullname varchar(50),
	gender varchar(12),
	age int,
	email varchar(150),
	phone_number varchar(20)
)

B2. Tao project + add thu vien
B3. Mapping tables <-> class object
B4. Tao DAO -> Lay thong tin/them/sua/xoa
	- Tim kiem (select)



Nguyễn Tiến Đạt [T2008A]
Nguyễn Tiến Đạt

2021-04-13 16:52:33


#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 Java2.lesson9.JSON.TongOn;

/**
 *
 * @author MyPC
 */
public class Student {
    String name, gender, rollNo, email, address;

    public Student() {
    }

    public Student(String name, String gender, String rollNo, String email, String address) {
        this.name = name;
        this.gender = gender;
        this.rollNo = rollNo;
        this.email = email;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

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

    public String getRollNo() {
        return rollNo;
    }

    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }

    public String getEmail() {
        return email;
    }

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

    public String getAddress() {
        return address;
    }

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

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


#StudentFrame.form


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

<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
  <NonVisualComponents>
    <Component class="javax.swing.JLabel" name="jLabel3">
      <Properties>
        <Property name="text" type="java.lang.String" value="jLabel3"/>
      </Properties>
    </Component>
  </NonVisualComponents>
  <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" alignment="0" attributes="0">
              <EmptySpace max="-2" attributes="0"/>
              <Component id="jPanel1" min="-2" max="-2" attributes="0"/>
              <EmptySpace pref="16" 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 max="-2" attributes="0"/>
              <Component id="jPanel1" max="32767" attributes="0"/>
              <EmptySpace max="-2" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Container class="javax.swing.JPanel" name="jPanel1">
      <Properties>
        <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
          <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
            <TitledBorder title="Quan Ly Sinh Vien"/>
          </Border>
        </Property>
      </Properties>

      <Layout>
        <DimensionLayout dim="0">
          <Group type="103" groupAlignment="0" attributes="0">
              <Group type="102" alignment="0" attributes="0">
                  <Group type="103" groupAlignment="0" attributes="0">
                      <Group type="102" attributes="0">
                          <EmptySpace max="-2" attributes="0"/>
                          <Group type="103" groupAlignment="0" attributes="0">
                              <Component id="jLabel1" alignment="0" min="-2" pref="54" max="-2" attributes="0"/>
                              <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
                              <Component id="jLabel4" alignment="0" min="-2" max="-2" attributes="0"/>
                              <Component id="jLabel5" alignment="0" min="-2" max="-2" attributes="0"/>
                              <Component id="jLabel6" alignment="0" min="-2" max="-2" attributes="0"/>
                          </Group>
                          <EmptySpace max="-2" attributes="0"/>
                          <Group type="103" groupAlignment="0" max="-2" attributes="0">
                              <Component id="txtName" max="32767" attributes="0"/>
                              <Component id="txtGender" max="32767" attributes="0"/>
                              <Component id="txtRollno" max="32767" attributes="0"/>
                              <Component id="txtEmail" max="32767" attributes="0"/>
                              <Component id="txtAddress" pref="403" max="32767" attributes="0"/>
                          </Group>
                      </Group>
                      <Group type="102" alignment="0" attributes="0">
                          <EmptySpace min="-2" pref="173" max="-2" attributes="0"/>
                          <Component id="btnUpdate" min="-2" pref="89" max="-2" attributes="0"/>
                          <EmptySpace min="-2" pref="59" max="-2" attributes="0"/>
                          <Component id="btnReset" min="-2" pref="87" max="-2" attributes="0"/>
                      </Group>
                  </Group>
                  <EmptySpace min="58" pref="58" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="0" max="-2" attributes="0">
                      <Component id="btnSearch" max="32767" attributes="0"/>
                      <Component id="btnImportXML" pref="90" max="32767" attributes="0"/>
                      <Component id="btnExportXML" pref="90" max="32767" attributes="0"/>
                      <Component id="btnImportJSON" pref="90" max="32767" attributes="0"/>
                      <Component id="btnEXportJSON" alignment="0" max="32767" attributes="0"/>
                  </Group>
                  <EmptySpace pref="86" 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="27" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="0" attributes="0">
                      <Group type="102" attributes="0">
                          <Group type="103" groupAlignment="1" max="-2" attributes="0">
                              <Group type="102" attributes="0">
                                  <EmptySpace min="-2" pref="4" max="-2" attributes="0"/>
                                  <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
                                  <EmptySpace max="32767" attributes="0"/>
                                  <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
                              </Group>
                              <Group type="102" attributes="0">
                                  <Component id="txtName" min="-2" max="-2" attributes="0"/>
                                  <EmptySpace min="-2" pref="25" max="-2" attributes="0"/>
                                  <Component id="txtGender" min="-2" max="-2" attributes="0"/>
                              </Group>
                          </Group>
                          <EmptySpace min="-2" pref="27" max="-2" attributes="0"/>
                          <Group type="103" groupAlignment="1" attributes="0">
                              <Component id="txtRollno" min="-2" max="-2" attributes="0"/>
                              <Component id="jLabel4" min="-2" max="-2" attributes="0"/>
                          </Group>
                          <EmptySpace min="-2" pref="22" max="-2" attributes="0"/>
                          <Group type="103" groupAlignment="1" attributes="0">
                              <Component id="txtEmail" min="-2" max="-2" attributes="0"/>
                              <Component id="jLabel5" min="-2" max="-2" attributes="0"/>
                          </Group>
                          <EmptySpace min="-2" pref="29" max="-2" attributes="0"/>
                          <Group type="103" groupAlignment="1" attributes="0">
                              <Component id="txtAddress" min="-2" max="-2" attributes="0"/>
                              <Component id="jLabel6" min="-2" max="-2" attributes="0"/>
                          </Group>
                          <EmptySpace max="32767" attributes="0"/>
                          <Group type="103" groupAlignment="0" max="-2" attributes="0">
                              <Component id="btnUpdate" pref="32" max="32767" attributes="0"/>
                              <Component id="btnReset" max="32767" attributes="0"/>
                          </Group>
                          <EmptySpace pref="20" max="32767" attributes="0"/>
                      </Group>
                      <Group type="102" attributes="0">
                          <Component id="btnSearch" min="-2" pref="36" max="-2" attributes="0"/>
                          <EmptySpace max="-2" attributes="0"/>
                          <Component id="btnImportXML" min="-2" pref="36" max="-2" attributes="0"/>
                          <EmptySpace max="-2" attributes="0"/>
                          <Component id="btnImportJSON" min="-2" pref="36" max="-2" attributes="0"/>
                          <EmptySpace max="-2" attributes="0"/>
                          <Component id="btnExportXML" min="-2" pref="36" max="-2" attributes="0"/>
                          <EmptySpace max="-2" attributes="0"/>
                          <Component id="btnEXportJSON" min="-2" pref="34" max="-2" attributes="0"/>
                          <EmptySpace max="32767" attributes="0"/>
                      </Group>
                  </Group>
              </Group>
          </Group>
        </DimensionLayout>
      </Layout>
      <SubComponents>
        <Component class="javax.swing.JLabel" name="jLabel1">
          <Properties>
            <Property name="text" type="java.lang.String" value="Ho Ten:"/>
          </Properties>
        </Component>
        <Component class="java.awt.TextField" name="txtName">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel2">
          <Properties>
            <Property name="text" type="java.lang.String" value="Gioi tinh:"/>
          </Properties>
        </Component>
        <Component class="java.awt.TextField" name="txtGender">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel4">
          <Properties>
            <Property name="text" type="java.lang.String" value="Roll No:"/>
          </Properties>
        </Component>
        <Component class="java.awt.TextField" name="txtRollno">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel5">
          <Properties>
            <Property name="text" type="java.lang.String" value="Email:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel6">
          <Properties>
            <Property name="text" type="java.lang.String" value="Dia chi:"/>
          </Properties>
        </Component>
        <Component class="java.awt.TextField" name="txtEmail">
        </Component>
        <Component class="java.awt.TextField" name="txtAddress">
        </Component>
        <Component class="java.awt.Button" name="btnUpdate">
          <Properties>
            <Property name="label" type="java.lang.String" value="Update"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnUpdateActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnSearch">
          <Properties>
            <Property name="label" type="java.lang.String" value="Search"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnSearchActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnImportXML">
          <Properties>
            <Property name="label" type="java.lang.String" value="Import XML"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnImportXMLActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnImportJSON">
          <Properties>
            <Property name="label" type="java.lang.String" value="Import JSON"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnImportJSONActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnExportXML">
          <Properties>
            <Property name="label" type="java.lang.String" value="Export XML"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnExportXMLActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnEXportJSON">
          <Properties>
            <Property name="label" type="java.lang.String" value="Export JSON"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnEXportJSONActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnReset">
          <Properties>
            <Property name="label" type="java.lang.String" value="Reset"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnResetActionPerformed"/>
          </Events>
        </Component>
      </SubComponents>
    </Container>
  </SubComponents>
</Form>


#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 Java2.lesson9.JSON.TongOn;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
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;
import javax.swing.JOptionPane;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author MyPC
 */
public class StudentFrame extends javax.swing.JFrame {

    List<Student> studentList = new ArrayList<>();

    /**
     * Creates new form StudentFrame
     */
    public StudentFrame() {
        initComponents();
    }

    /**
     * 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() {

        jLabel3 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtName = new java.awt.TextField();
        jLabel2 = new javax.swing.JLabel();
        txtGender = new java.awt.TextField();
        jLabel4 = new javax.swing.JLabel();
        txtRollno = new java.awt.TextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtEmail = new java.awt.TextField();
        txtAddress = new java.awt.TextField();
        btnUpdate = new java.awt.Button();
        btnSearch = new java.awt.Button();
        btnImportXML = new java.awt.Button();
        btnImportJSON = new java.awt.Button();
        btnExportXML = new java.awt.Button();
        btnEXportJSON = new java.awt.Button();
        btnReset = new java.awt.Button();

        jLabel3.setText("jLabel3");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Quan Ly Sinh Vien"));

        jLabel1.setText("Ho Ten:");

        jLabel2.setText("Gioi tinh:");

        jLabel4.setText("Roll No:");

        jLabel5.setText("Email:");

        jLabel6.setText("Dia chi:");

        btnUpdate.setLabel("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnSearch.setLabel("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        btnImportXML.setLabel("Import XML");
        btnImportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportXMLActionPerformed(evt);
            }
        });

        btnImportJSON.setLabel("Import JSON");
        btnImportJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportJSONActionPerformed(evt);
            }
        });

        btnExportXML.setLabel("Export XML");
        btnExportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportXMLActionPerformed(evt);
            }
        });

        btnEXportJSON.setLabel("Export JSON");
        btnEXportJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEXportJSONActionPerformed(evt);
            }
        });

        btnReset.setLabel("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(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()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtGender, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtRollno, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtEmail, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(173, 173, 173)
                        .addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(59, 59, 59)
                        .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(58, 58, 58)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnImportXML, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                    .addComponent(btnExportXML, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                    .addComponent(btnImportJSON, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                    .addComponent(btnEXportJSON, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(86, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(4, 4, 4)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel2))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(25, 25, 25)
                                .addComponent(txtGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(27, 27, 27)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtRollno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addGap(22, 22, 22)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addGap(29, 29, 29)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                            .addComponent(btnReset, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap(20, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnImportXML, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnImportJSON, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExportXML, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEXportJSON, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );

        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()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    int checkSearch;
    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        checkSearch = 0;
        if (txtRollno.getText().isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Yeu cau nhap Rollno can tim kiem!!");
        } else {
            Connection conn = null;
            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/T2008A", "root", "");
                String sql = "select * from quanlysinhvien where Rollno like '%" + txtRollno.getText() + "%'";
                PreparedStatement statement = (PreparedStatement) conn.prepareStatement(sql);
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    Student student = new Student(resultSet.getString("Name"),
                            resultSet.getString("Gender"),
                            resultSet.getString("Rollno"),
                            resultSet.getString("Email"),
                            resultSet.getString("Address"));
                    txtName.setText(student.getName());
                    txtGender.setText(student.getGender());
                    txtRollno.setText(student.getRollNo());
                    txtEmail.setText(student.getEmail());
                    txtAddress.setText(student.getAddress());
                    checkSearch = 1;
                }
            } catch (SQLException ex) {
                Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (checkSearch == 0) {
                    JOptionPane.showMessageDialog(rootPane, "Khong tim thay sinh vien nao!!");
                }
            }
        }
    }//GEN-LAST:event_btnSearchActionPerformed

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        // TODO add your handling code here:
        if (checkSearch == 0) {
            JOptionPane.showMessageDialog(rootPane, "Yeu cau tim kiem sinh vien truoc!!");
        } else {
            Connection conn = null;
            try {
                String sql = "update quanlysinhvien set Name = ?, Gender = ?, Email = ?, Address = ? where Rollno = ?";
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/T2008A", "root", "");
                PreparedStatement statement = (PreparedStatement) conn.prepareStatement(sql);

                statement.setString(1, txtName.getText());
                statement.setString(2, txtGender.getText());
                statement.setString(3, txtEmail.getText());
                statement.setString(4, txtAddress.getText());
                statement.setString(5, txtRollno.getText());
                statement.execute();
            } catch (SQLException ex) {
                Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
//                btnResetActionPerformed(evt);
                JOptionPane.showMessageDialog(rootPane, "Update thanh cong!!");
            }
        }
    }//GEN-LAST:event_btnUpdateActionPerformed

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

    private void btnImportXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportXMLActionPerformed
        // TODO add your handling code here:
        try {
            File file = new File("student.xml");
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            StudentParser studentParser = new StudentParser();
            parser.parse(file, studentParser);
            studentList = studentParser.studentList;
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/T2008A", "root", "");
            for (Student student : studentList) {
                String sql = "select * from quanlysinhvien";
                sql += " where Rollno like '%" + student.getRollNo() + "%'";
                PreparedStatement statement = conn.prepareStatement(sql);
                ResultSet resultSet = statement.executeQuery();
                int check = 0;
                while (resultSet.next()) {
                    check++;
                }
                if (check == 0) {
                    String sql1 = "insert into quanlysinhvien(Name, Gender, Rollno, Email, Address) values (?, ?, ?, ?, ?)";
                    PreparedStatement statement1 = conn.prepareStatement(sql1);
                    statement1.setString(1, student.getName());
                    statement1.setString(2, student.getGender());
                    statement1.setString(3, student.getRollNo());
                    statement1.setString(4, student.getEmail());
                    statement1.setString(5, student.getAddress());
                    statement1.execute();
                } else {
                    String sql2 = "update quanlysinhvien set Name = ?, Gender = ?, Email = ?, Address = ? where Rollno = ?";
                    PreparedStatement statement2 = conn.prepareStatement(sql2);
                    statement2.setString(1, student.getName());
                    statement2.setString(2, student.getGender());
                    statement2.setString(3, student.getEmail());
                    statement2.setString(4, student.getAddress());
                    statement2.setString(5, student.getRollNo());
                    statement2.execute();
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            JOptionPane.showMessageDialog(rootPane, "Import thanh cong!!");
        }
    }//GEN-LAST:event_btnImportXMLActionPerformed

    private void btnImportJSONActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportJSONActionPerformed
        // TODO add your handling code here:
        File file = new File("student.json");
        try {
            FileReader reader = new FileReader(file);
            Gson gson = new Gson();
            java.lang.reflect.Type type = new TypeToken<ArrayList<Student>>() {
            }.getType();
            studentList = gson.fromJson(reader, type);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/T2008A", "root", "");
            for (Student student : studentList) {
                String sql = "select * from quanlysinhvien";
                sql += " where Rollno like '%" + student.getRollNo() + "%'";
                PreparedStatement statement = conn.prepareStatement(sql);
                ResultSet resultSet = statement.executeQuery();
                int check = 0;
                while (resultSet.next()) {
                    check++;
                }
                if (check == 0) {
                    String sql1 = "insert into quanlysinhvien(Name, Gender, Rollno, Email, Address) values (?, ?, ?, ?, ?)";
                    PreparedStatement statement1 = conn.prepareStatement(sql1);
                    statement1.setString(1, student.getName());
                    statement1.setString(2, student.getGender());
                    statement1.setString(3, student.getRollNo());
                    statement1.setString(4, student.getEmail());
                    statement1.setString(5, student.getAddress());
                    statement1.execute();
                } else {
                    String sql2 = "update quanlysinhvien set Name = ?, Gender = ?, Email = ?, Address = ? where Rollno = ?";
                    PreparedStatement statement2 = conn.prepareStatement(sql2);
                    statement2.setString(1, student.getName());
                    statement2.setString(2, student.getGender());
                    statement2.setString(3, student.getEmail());
                    statement2.setString(4, student.getAddress());
                    statement2.setString(5, student.getRollNo());
                    statement2.execute();
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            JOptionPane.showMessageDialog(rootPane, "Import thanh cong!!");
        }
    }//GEN-LAST:event_btnImportJSONActionPerformed

    private void btnExportXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportXMLActionPerformed
        // TODO add your handling code here:
        try {
            File file = new File("student.xml");
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            StudentParser studentParser = new StudentParser();
            parser.parse(file, studentParser);
            studentList = studentParser.studentList;
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        String rollNoSearch = JOptionPane.showInputDialog("Nhap RollNo can tim kiem:");
        int check = 0;
        for (Student student : studentList) {
            if(student.getRollNo().equalsIgnoreCase(rollNoSearch)){
                check++;
                txtName.setText(student.getName());
                txtGender.setText(student.getGender());
                txtRollno.setText(student.getRollNo());
                txtEmail.setText(student.getEmail());
                txtAddress.setText(student.getAddress());
                break;
            }
        }
        if(check == 0){
            JOptionPane.showMessageDialog(rootPane, "Khong tim thay sinh vien nao!!");
            txtName.setText("");
            txtGender.setText("");
            txtRollno.setText("");
            txtEmail.setText("");
            txtAddress.setText("");
        }
    }//GEN-LAST:event_btnExportXMLActionPerformed

    private void btnEXportJSONActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEXportJSONActionPerformed
        // TODO add your handling code here:
        File file = new File("student.json");
        try {
            FileReader reader = new FileReader(file);
            Gson gson = new Gson();
            java.lang.reflect.Type type = new TypeToken<ArrayList<Student>>() {
            }.getType();
            studentList = gson.fromJson(reader, type);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        String rollNoSearch = JOptionPane.showInputDialog("Nhap RollNo can tim kiem:");
        int check = 0;
        for (Student student : studentList) {
            if(student.getRollNo().equalsIgnoreCase(rollNoSearch)){
                check++;
                txtName.setText(student.getName());
                txtGender.setText(student.getGender());
                txtRollno.setText(student.getRollNo());
                txtEmail.setText(student.getEmail());
                txtAddress.setText(student.getAddress());
                break;
            }
        }
        if(check == 0){
            JOptionPane.showMessageDialog(rootPane, "Khong tim thay sinh vien nao!!");
            txtName.setText("");
            txtGender.setText("");
            txtRollno.setText("");
            txtEmail.setText("");
            txtAddress.setText("");
        }
    }//GEN-LAST:event_btnEXportJSONActionPerformed

    /**
     * @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 java.awt.Button btnEXportJSON;
    private java.awt.Button btnExportXML;
    private java.awt.Button btnImportJSON;
    private java.awt.Button btnImportXML;
    private java.awt.Button btnReset;
    private java.awt.Button btnSearch;
    private java.awt.Button btnUpdate;
    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.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private java.awt.TextField txtAddress;
    private java.awt.TextField txtEmail;
    private java.awt.TextField txtGender;
    private java.awt.TextField txtName;
    private java.awt.TextField txtRollno;
    // End of variables declaration//GEN-END:variables
}


#StudentParser.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 Java2.lesson9.JSON.TongOn;

import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author MyPC
 */
public class StudentParser extends DefaultHandler{
    List<Student> studentList = new ArrayList<>();
    Student student = null;
    
    boolean isStudent = false;
    boolean isName = false;
    boolean isGender = false;
    boolean isRollno = false;
    boolean isEmail = false;
    boolean isAddress = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if(qName.equalsIgnoreCase("student")){
            student = new Student();
            isStudent = true;
        }
        if(isStudent){
            if(qName.equalsIgnoreCase("name")){
                isName = true;
            }else if(qName.equalsIgnoreCase("gender")){
                isGender = true;
            }else if(qName.equalsIgnoreCase("rollno")){
                isRollno = true;
            }else if(qName.equalsIgnoreCase("email")){
                isEmail = true;
            }else if(qName.equalsIgnoreCase("address")){
                isAddress = true;
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(qName.equalsIgnoreCase("student")){
            isStudent = false;
            studentList.add(student);
            student = null;
        }
        if(isStudent){
            if(qName.equalsIgnoreCase("name")){
                isName = false;
            }else if(qName.equalsIgnoreCase("gender")){
                isGender = false;
            }else if(qName.equalsIgnoreCase("rollno")){
                isRollno = false;
            }else if(qName.equalsIgnoreCase("email")){
                isEmail = false;
            }else if(qName.equalsIgnoreCase("address")){
                isAddress = false;
            }
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String str = String.valueOf(ch, start, length);
        if(isStudent){
            if(isName){
                student.setName(str);
            }else if(isGender){
                student.setGender(str);
            }else if(isRollno){
                student.setRollNo(str);
            }else if(isEmail){
                student.setEmail(str);
            }else if(isAddress){
                student.setAddress(str);
            }
        }
    }
    
    
    
    
}



Do Trung Duc [T2008A]
Do Trung Duc

2021-04-13 16:27:17



/*
 * 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 LT.JSON;

/**
 *
 * @author TrungDuc
 */
public class Student {

    String name, gender, roolno, email, address;
    int id;

    public Student() {
    }

    public Student(String name, String gender, String roolno, String email, String address) {
        this.name = name;
        this.gender = gender;
        this.roolno = roolno;
        this.email = email;
        this.address = address;
    }

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

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

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

    public String getRoolno() {
        return roolno;
    }

    public void setRoolno(String roolno) {
        this.roolno = roolno;
    }

    public String getEmail() {
        return email;
    }

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

    public String getAddress() {
        return address;
    }

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

    public void Display() {
        System.out.println(this);
    }

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

    public String toXML() {
        return "	<student>\n"
                + "		<name>"+name+"</name>\n"
                + "		<gender>"+gender+"</gender>\n"
                + "		<roolno>"+roolno+"</roolno>\n"
                + "		<email>"+email+"</email>\n"
                + "		<address>"+address+"</address>\n"
                + "	</student>\n";
    }

}



Do Trung Duc [T2008A]
Do Trung Duc

2021-04-13 16:27:06



/*
 * 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 LT.JSON;

import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author TrungDuc
 */
public class studentParse extends DefaultHandler {

   public static ArrayList<Student> studentList = new ArrayList<>();
    boolean isStudent = false;
    boolean isName = false;
    boolean isGender = false;
    boolean isRoolno = false;
    boolean isEmail = false;
    boolean isAddress = false;
    Student student = null;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equalsIgnoreCase("student")) {
            isStudent = true;
            student = new Student();
        }

        if (isStudent) {
            if (qName.equalsIgnoreCase("name")) {
                isName = true;
            } else if (qName.equalsIgnoreCase("gender")) {
                isGender = true;
            } else if (qName.equalsIgnoreCase("roolno")) {
                isRoolno = true;
            } else if (qName.equalsIgnoreCase("email")) {
                isEmail = true;
            } else if (qName.equalsIgnoreCase("address")) {
                isAddress = true;
            }
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String str = String.valueOf(ch, start, length);
        if (isStudent) {
            if (isName) {
                student.setName(str);
            } else if (isGender) {
                student.setGender(str);
            } else if (isRoolno) {
                student.setRoolno(str);
            } else if (isEmail) {
                student.setEmail(str);
            } else if (isAddress) {
                student.setAddress(str);
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equalsIgnoreCase("student")) {
            isStudent = false;
            studentList.add(student);
            student = null;
        }

        if (isStudent) {
            if (qName.equalsIgnoreCase("name")) {
                isName = false;
            } else if (qName.equalsIgnoreCase("gender")) {
                isGender = false;
            } else if (qName.equalsIgnoreCase("roolno")) {
                isRoolno = false;
            } else if (qName.equalsIgnoreCase("email")) {
                isEmail = false;
            } else if (qName.equalsIgnoreCase("address")) {
                isAddress = false;
            }
        }
    }

}



Do Trung Duc [T2008A]
Do Trung Duc

2021-04-13 16:26:54



/*
 * 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 LT.JSON;

import com.mysql.cj.protocol.Resultset;
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 TrungDuc
 */
public class ConnectToMySql {

    static List<Student> studentList = new ArrayList<>();

    public static List<Student> readData(String findRoolno) {
        Connection conn = null;

        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");

            String sql = "";
            if (findRoolno.isEmpty()) {
                sql = "select * from students";
            } else {
                sql = "select * from students where roolno like '%" + findRoolno + "%'";
            }

            PreparedStatement statement = conn.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                Student student = new Student(resultSet.getInt("id"),
                        resultSet.getString("name"),
                        resultSet.getString("gender"),
                        resultSet.getString("roolno"),
                        resultSet.getString("email"),
                        resultSet.getString("address")
                );
                studentList.add(student);
            }

        } catch (SQLException ex) {
            Logger.getLogger(ConnectToMySql.class.getName()).log(Level.SEVERE, null, ex);
        }
        return studentList;
    }

    public static void updateData(Student student, int id) {
        Connection conn = null;

        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            String sql = "update students set name = ?, gender = ?, roolno = ?, email =?, address = ? where id = ?";

            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, student.getName());
            statement.setString(2, student.getGender());
            statement.setString(3, student.getRoolno());
            statement.setString(4, student.getEmail());
            statement.setString(5, student.getAddress());
            statement.setInt(6, id);

            statement.execute();

        } catch (SQLException ex) {
            Logger.getLogger(ConnectToMySql.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(ConnectToMySql.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
       public static void updateData(Student student, String roono) {
        Connection conn = null;

        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            String sql = "update students set name = ?, gender = ?, roolno = ?, email =?, address = ? where roolno = ?";

            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, student.getName());
            statement.setString(2, student.getGender());
            statement.setString(3, student.getRoolno());
            statement.setString(4, student.getEmail());
            statement.setString(5, student.getAddress());
             statement.setString(6, student.getRoolno());
            statement.execute();

        } catch (SQLException ex) {
            Logger.getLogger(ConnectToMySql.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(ConnectToMySql.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
       
       public static void addData(Student student){
           Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            String sql = "insert into students(name,gender,roolno,email,address) values(?,?,?,?,?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, student.getName());
            statement.setString(2, student.getGender());
            statement.setString(3, student.getRoolno());
            statement.setString(4, student.getEmail());
            statement.setString(5, student.getAddress());
            
            statement.execute();
            
        } catch (SQLException ex) {
            Logger.getLogger(ConnectToMySql.class.getName()).log(Level.SEVERE, null, ex);
        }
                   
       }
    
    

}



Do Trung Duc [T2008A]
Do Trung Duc

2021-04-13 16:25:27



/*
 * 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 LT.JSON;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author TrungDuc
 */
public class Main extends javax.swing.JFrame {

    List<Student> studentList = new ArrayList<>();
    DefaultTableModel tableModel;
    int index = -1;
    int idUpdate;

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
        tableModel = (DefaultTableModel) tblStudent.getModel();

        tblStudent.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                index = tblStudent.getSelectedRow();

                txtname.setText(studentList.get(index).getName());
                txtgender.setText(studentList.get(index).getGender());
                txtroolno.setText(studentList.get(index).getRoolno());
                txtemail.setText(studentList.get(index).getEmail());
                txtaddress.setText(studentList.get(index).getAddress());

                idUpdate = studentList.get(index).getId();
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
    }

    /**
     * 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">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtname = new javax.swing.JTextField();
        txtgender = new javax.swing.JTextField();
        txtroolno = new javax.swing.JTextField();
        txtemail = new javax.swing.JTextField();
        txtaddress = new javax.swing.JTextField();
        btnsearch = new javax.swing.JButton();
        btn_importxml = new javax.swing.JButton();
        btn_importJson = new javax.swing.JButton();
        btn_exportXML = new javax.swing.JButton();
        btn_exportJson = new javax.swing.JButton();
        btnupdate = new javax.swing.JButton();
        btnreset = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblStudent = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Ho Ten");

        jLabel2.setText("Gioi tinh ");

        jLabel3.setText("Roolno");

        jLabel4.setText("Email");

        jLabel5.setText("Dia chi");

        txtgender.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtgenderActionPerformed(evt);
            }
        });

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

        btn_importxml.setText("Import XML");
        btn_importxml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_importxmlActionPerformed(evt);
            }
        });

        btn_importJson.setText("Import Json");
        btn_importJson.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_importJsonActionPerformed(evt);
            }
        });

        btn_exportXML.setText("Export XML");
        btn_exportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_exportXMLActionPerformed(evt);
            }
        });

        btn_exportJson.setText("Export Json");
        btn_exportJson.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_exportJsonActionPerformed(evt);
            }
        });

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

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

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

            },
            new String [] {
                "Ho Ten", "Gioi Tinh", "Roolno", "Email", "Dia chi"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblStudent);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(51, 51, 51)
                                .addComponent(txtaddress, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtemail, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                                    .addComponent(txtroolno)
                                    .addComponent(txtgender)
                                    .addComponent(txtname))))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btn_importxml, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btn_importJson)
                            .addComponent(btn_exportXML)
                            .addComponent(btn_exportJson)
                            .addComponent(btnsearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addComponent(btnupdate)
                        .addGap(38, 38, 38)
                        .addComponent(btnreset))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnsearch))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtgender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_importxml))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtroolno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_importJson))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .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)
                    .addComponent(btn_exportXML))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.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)
                    .addComponent(btn_exportJson))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnupdate)
                    .addComponent(btnreset))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(126, 126, 126))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 105, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void txtgenderActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    private void btnsearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        String roolnoFind = JOptionPane.showInputDialog("Nhap roolno can tim...");
        if (roolnoFind.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Ban phai nhap roolno can tim");
            return;
        }
        studentList = ConnectToMySql.readData(roolnoFind);
        Display();
    }                                         

    private void btnresetActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        tableModel.setRowCount(0);
    }                                        

    private void btnupdateActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        if (index >= 0) {
            Student student = new Student();
            student.setName(txtname.getText());
            student.setGender(txtgender.getText());
            student.setRoolno(txtroolno.getText());
            student.setEmail(txtemail.getText());
            student.setAddress(txtaddress.getText());

            studentList.set(index, student);
            Display();

            ConnectToMySql.updateData(student, idUpdate);
        }

    }                                         

    private void btn_exportXMLActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
        String studentListString = "";
        for (Student student : studentList) {
            studentListString += student.toXML();
        }

        String contendString = "<student-List>"
                + studentListString
                + "</student-List>";

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("studentManager.xml");
            byte[] data = contendString.getBytes("utf8");
            fos.write(data);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Da luu du lieu vao file XML");
    }                                             

    private void btn_importxmlActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:

        File file = new File("studentManager.xml");
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parse;

        int countAddNew = 0;
        try {
            parse = factory.newSAXParser();
            studentParse stdParse = new studentParse();
            parse.parse(file, stdParse);
            studentList = stdParse.studentList;
            Display();
            List<Student> studentListDb = ConnectToMySql.readData("");
            for (Student student : studentList) {
                boolean exits = false;
                for (Student studentDB : studentListDb) {
                    if (student.getRoolno().equalsIgnoreCase(studentDB.getRoolno())) {
                        ConnectToMySql.updateData(student, student.getRoolno());
                        exits = true;
                    }
                }
                if (exits == false) {
                    ConnectToMySql.addData(student);
                    countAddNew++;
                }
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (countAddNew > 0) {
            JOptionPane.showMessageDialog(rootPane, "Da them moi cac phan tu vao DataBase");
        }
    }                                             

    private void btn_exportJsonActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        Gson gson = new Gson();
        String json = gson.toJson(studentList);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("student.json");
            byte[] data = json.getBytes("utf8");
            fos.write(data);
            JOptionPane.showMessageDialog(rootPane, "Da luu du lieu xuong File JSON");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }                                              

    private void btn_importJsonActionPerformed(java.awt.event.ActionEvent evt) {                                               

        // TODO add your handling code here:
        FileReader reader = null;
        try {
            int countAddNew = 0;
            File file = new File("student.json");
            reader = new FileReader(file);
            Gson gson = new Gson();
            java.lang.reflect.Type type = new TypeToken<List<Student>>() {}.getType();
            studentList = gson.fromJson(reader, type);
            Display();

            List<Student> studentListDb = ConnectToMySql.readData("");
            for (Student student : studentList) {
                boolean exits = false;
                for (Student studentDB : studentListDb) {
                    if (student.getRoolno().equalsIgnoreCase(studentDB.getRoolno())) {
                        ConnectToMySql.updateData(student, student.getRoolno());
                        exits = true;
                    }
                }
                if (exits == false) {
                    ConnectToMySql.addData(student);
                    countAddNew++;
                }
            }
            if(countAddNew>0){
                JOptionPane.showMessageDialog(rootPane, "Da them du lieu vao DataBase");
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }                                              

    private void Display() {
        tableModel.setRowCount(0);
        for (Student student : studentList) {
            student.Display();
            tableModel.addRow(new Object[]{
                student.getName(),
                student.getGender(),
                student.getRoolno(),
                student.getEmail(),
                student.getAddress()
            });
        }
    }

    /**
     * @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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.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 Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btn_exportJson;
    private javax.swing.JButton btn_exportXML;
    private javax.swing.JButton btn_importJson;
    private javax.swing.JButton btn_importxml;
    private javax.swing.JButton btnreset;
    private javax.swing.JButton btnsearch;
    private javax.swing.JButton btnupdate;
    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 txtaddress;
    private javax.swing.JTextField txtemail;
    private javax.swing.JTextField txtgender;
    private javax.swing.JTextField txtname;
    private javax.swing.JTextField txtroolno;
    // End of variables declaration                   
}



NguyenHuuThanh [T1907A]
NguyenHuuThanh

2020-04-23 21:43:42



/*
 * 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 javaimportexportxmlandjson;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.json.JSONArray;
import org.xml.sax.SAXException;

/**
 *
 * @author abc
 */
public class StudentJForm extends javax.swing.JFrame {

    /**
     * Creates new form StudentJForm
     */
    public StudentJForm() {
        initComponents();
    }

    /**
     * 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">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtRollNo = new javax.swing.JTextField();
        txtFullname = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        txtAddress = new javax.swing.JTextField();
        txtGender = new javax.swing.JComboBox<>();
        btnSearch = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        btnImportToXML = new javax.swing.JButton();
        btnExportToXML = new javax.swing.JButton();
        btnImportToJSON = new javax.swing.JButton();
        btnExportToJSON = new javax.swing.JButton();
        txtEmail = new javax.swing.JTextField();
        btnSave = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Roll No");

        jLabel2.setText("Full Name");

        jLabel3.setText("Gender");

        jLabel4.setText("Email");

        jLabel5.setText("Address");

        jTextField3.setText("jTextField3");

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

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

        btnUpdate.setText("Update");

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

        btnImportToXML.setText("Import to XML");
        btnImportToXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportToXMLActionPerformed(evt);
            }
        });

        btnExportToXML.setText("Export to XML");
        btnExportToXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportToXMLActionPerformed(evt);
            }
        });

        btnImportToJSON.setText("Import to JSON");
        btnImportToJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportToJSONActionPerformed(evt);
            }
        });

        btnExportToJSON.setText("Export to JSON");
        btnExportToJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportToJSONActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(75, 75, 75)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4))
                        .addGap(44, 44, 44)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txtFullname, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(txtRollNo))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(57, 57, 57)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSave)
                        .addGap(62, 62, 62)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnImportToJSON)
                    .addComponent(btnExportToXML)
                    .addComponent(btnReset)
                    .addComponent(btnUpdate)
                    .addComponent(btnSearch)
                    .addComponent(btnImportToXML)
                    .addComponent(btnExportToJSON))
                .addGap(89, 89, 89))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(btnSearch)
                .addGap(1, 1, 1)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel1)
                                    .addComponent(txtRollNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(55, 55, 55))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGap(35, 35, 35)
                                .addComponent(btnUpdate)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtFullname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(1, 1, 1)
                        .addComponent(btnReset)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(36, 36, 36)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel3)
                                    .addComponent(txtGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(42, 42, 42)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(btnImportToXML)
                                    .addComponent(btnSave))))
                        .addGap(39, 39, 39)
                        .addComponent(btnExportToXML)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .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))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(69, 69, 69)
                        .addGroup(jPanel1Layout.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(48, 48, 48))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(btnImportToJSON)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnExportToJSON)
                        .addGap(29, 29, 29))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 112, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        txtRollNo.setText("");
        txtFullname.setText("");
        txtGender.setSelectedIndex(0);
        txtEmail.setText("");
        txtAddress.setText("");
        
    }                                        

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
       int rollno = Integer.parseInt(txtRollNo.getText());
       String fullname = txtFullname.getText();
       String gender = txtGender.getSelectedItem().toString();
       String address = txtAddress.getText();
       String email = txtEmail.getText();
       
       if ( fullname.isEmpty())
       {
           JOptionPane.showMessageDialog(rootPane, "Empty fullname ");
           return;
       }
       
       Student std = new Student(rollno , fullname , gender , email ,address );
       
       Studentmodify.save(std);
           
       
    }                                       

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        
        int rollno = Integer.parseInt(txtRollNo.getText());
        
        Student std = Studentmodify.find(rollno);
        
        if (std == null)
        {
            JOptionPane.showMessageDialog(rootPane, "Not found any student");
            return ;
        }
        
        txtFullname.setText(std.getFullname());
        txtEmail.setText(std.getEmail());
        txtAddress.setText(std.getAddress());
        txtGender.setSelectedItem(std.getGender());
    }                                         

    private void btnExportToXMLActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        File file = null ;
       
       
       JFileChooser fileChooser = new JFileChooser();
  if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        file = fileChooser.getSelectedFile();
  // save to file
}
  
    if (file == null)
    {
        JOptionPane.showMessageDialog(rootPane, "Not save");
    }
        List<Student> studentList = searchStudents();
        
        FileOutputStream fos = null;
        try {
            
            
             fos = new FileOutputStream("file"); // name;
           
             String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                     "<student>";
             
             fos.write(str.getBytes());
             
             for (Student std : studentList)
             {
                 fos.write(std.getXMLString().getBytes());
             }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
        } finally
        {
            if (fos != null)
            {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export thanh cong");
        
        
    }                                              

    private void btnExportToJSONActionPerformed(java.awt.event.ActionEvent evt) {                                                
        // TODO add your handling code here:
        
        // Export JSON
       /* List<Student> studentList = searchStudents();
        // convert List to JSON file
        JSONArray arr = new JSONArray(studentList);
        System.out.println(arr.toString());*/
       File file = null ;
       
       
       JFileChooser fileChooser = new JFileChooser();
  if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        file = fileChooser.getSelectedFile();
  // save to file
}
  
    if (file == null)
    {
        JOptionPane.showMessageDialog(rootPane, "Not save");
    }
        
        // Export to file
        FileOutputStream fos = null;
        try {
            List<Student> studentList = searchStudents();
            JSONArray arr = new JSONArray(studentList);
            
             fos = new FileOutputStream("file"); // name;
             byte[] b = arr.toString().getBytes();
             
             fos.write(b);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
        } finally
        {
            if (fos != null)
            {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export thanh cong");
        

    }                                               

    private void btnImportToJSONActionPerformed(java.awt.event.ActionEvent evt) {                                                
        // TODO add your handling code here:
         
         FileReader reader = null;
        
        
        try {
             File file = null;
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
         file = fileChooser.getSelectedFile();
  // load from file
}
        if (file == null)
        {
            JOptionPane.showMessageDialog(rootPane, "not file selected");
            return ;
        }
           java.lang.reflect.Type classOfT = new TypeToken<ArrayList<Student>>(){}.getType();
            reader = new FileReader(file);
            Gson gson = new Gson();
            ArrayList<Student> list = gson.fromJson(reader, classOfT);
            
            for (Student std : list) {
                Studentmodify.save(std);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
            
            
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            
        }
            
        
    }                                               

    private void btnImportToXMLActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        FileInputStream fis = null;
        List<Student> studentList = null;
        try {
            fis = new FileInputStream("student.xml");
            SAXParserFactory factory = SAXParserFactory.newInstance();
            
            SAXParser parser = factory.newSAXParser();
            
            StudentHandler handler = new StudentHandler();
            
            parser.parse(fis, handler);
            
            studentList = handler.getStudentlist();
            
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
        } finally 
        {
            if(fis != null)
            {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(StudentJForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }                                              

    private List<Student> searchStudents()
    {
                String searchValue = JOptionPane.showInputDialog("Input search value");
        
        List<Student> studentList = null;
        
        if (searchValue.isEmpty())
        {
            studentList = Studentmodify.findAll();
        }
        else 
        {
            studentList = Studentmodify.findByRollNoorFullname(searchValue);
            
            
        }
        
        JOptionPane.showMessageDialog(rootPane, "size :" + studentList.size());
        return studentList;
    }
    /**
     * @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(StudentJForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StudentJForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StudentJForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StudentJForm.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 StudentJForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnExportToJSON;
    private javax.swing.JButton btnExportToXML;
    private javax.swing.JButton btnImportToJSON;
    private javax.swing.JButton btnImportToXML;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnUpdate;
    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.JTextField jTextField3;
    private javax.swing.JTextField txtAddress;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtFullname;
    private javax.swing.JComboBox<String> txtGender;
    private javax.swing.JTextField txtRollNo;
    // End of variables declaration                   
}
/*
 * 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 javaimportexportxmlandjson;

/**
 *
 * @author abc
 */
public class Student {
    int rollno ; 
    String fullname , gender , email , address ;
    
    public Student()
    {
        
    }

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

    public int getRollno() {
        return rollno;
    }

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

    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 getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "Student{" + "rollno=" + rollno + ", fullname=" + fullname + ", gender=" + gender + ", email=" + email + ", address=" + address + '}';
    }
    
    public void display()
    {
        System.out.println(this);
    }
    
    public String getXMLString()
    {
        return "<student>\n" +
"<rollno>" + rollno + "</rollno>\n" +
"<fullname>"+fullname+"</fullname>\n" +
"<email>"+email+"</email>\n" +
"<gender>"+gender+"</gender>\n" +
"<address>"+address+"</address>\n" +
"</student>";
    }
    
    
}
/*
 * 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 javaimportexportxmlandjson;

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;

/**
 *
 * @author abc
 */
public class Studentmodify {
    public static List<Student> findAll()
    {
        Connection conn = null ;
        Statement statement = null ;
        List<Student> studentList = new ArrayList<>();
        try {
            // Lấy tất cả sinh viên
            
            // B1 : mở connection tới dtb

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanaging?serverTimezone=UTC" , "root" , "");
        
            
            // B2 : Query
            
            statement = conn.createStatement();
            String sql = "select * from student";
            
            // Lấy dữ liệu trả về :
            
            ResultSet resultSet = statement.executeQuery(sql);
            
            // Lấy bảng ghi dữ liệu resultset -> lưu vào biến
            
            while (resultSet.next())
            {
                Student std = new Student(
                resultSet.getInt("rollno"),
                resultSet.getString("fullname"),
                resultSet.getString("gender"),
                resultSet.getString("email"),
                resultSet.getString("address")
                );
                
                studentList.add(std);
            }
            
            
            
        } catch (SQLException ex) {
            Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
            if(conn != null)
            {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null)
            {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return studentList;
    }
    
    
    private static void insert(Student std)
    {
        Connection conn = null ;
        PreparedStatement statement = null ;
        List<Student> studentList = new ArrayList<>();
        try {
            // Lấy tất cả sinh viên
            
            // B1 : mở connection tới dtb

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanaging", "root", "");
        
            String sql = "insert into student(rollno , fullname , gender , email ,address)"
                    + "values (?, ? ,? ,? ,?)";
            
            statement = conn.prepareStatement(sql);
            
            statement.setInt(1, std.getRollno());
            statement.setString(2 , std.getFullname());
            statement.setString(3 , std.getGender());
            statement.setString(4, std.getEmail());
            statement.setString(5, std.getAddress());
            
            statement.execute();
           
        } catch (SQLException ex) {
            Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
            if(conn != null)
            {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null)
            {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
        
        private static void update(Student std)
    {
        Connection conn = null ;
        PreparedStatement statement = null ;
        List<Student> studentList = new ArrayList<>();
        try {
            // Lấy tất cả sinh viên
            
            // B1 : mở connection tới dtb

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanaging", "root", "");
        
            String sql = "update student set fullname = ? , gender = ? , email = ? , address = ?"
                    + "where rollno = ?";
            
            statement = conn.prepareStatement(sql);
            
            
            statement.setString(1 , std.getFullname());
            statement.setString(2 , std.getGender());
            statement.setString(3, std.getEmail());
            statement.setString(4, std.getAddress());
            statement.setInt(5, std.getRollno());
            
            statement.execute();
           
        } catch (SQLException ex) {
            Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
            if(conn != null)
            {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null)
            {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
      
    }
        
        public static void save(Student std)
        {
            std = find(std.getRollno());
            
            if (std == null)
            {
                insert(std);
            }
            else 
            {
                update(std);
            }
            
            
            
        }
        
        public static Student find(int rollno)
        {
        Connection conn = null ;
        PreparedStatement statement = null ;
        
        try {
            // Lấy tất cả sinh viên
            
            // B1 : mở connection tới dtb

            
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanaging", "root", "");
            String sql = "select * from student where rollno = ?";
            statement = conn.prepareStatement(sql);
            
            statement.setInt(1 , rollno);
            
            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next())
            {
                Student std = new Student(
                        resultSet.getInt("rollno"),
                        resultSet.getString("fullname"),
                        resultSet.getString("gender"),
                        resultSet.getString("email"),
                        resultSet.getString("address")
                );
                
                return std ;
            }
            
            
            
            
            
            statement.execute();
           
        } catch (SQLException ex) {
            Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
            if(conn != null)
            {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null)
            {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null ;
        }
        
         public static void delete(int rollno)
        {
        Connection conn = null ;
        PreparedStatement statement = null ;
        
        try {
            // Lấy tất cả sinh viên
            
            // B1 : mở connection tới dtb

            
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanaging", "root", "");
            
            
            String sql = "delete from student where rollno = ?";
            statement = conn.prepareStatement(sql);
            
            statement.setInt(1 , rollno);
            
            statement.execute();
            
            
            
            
            
            statement.execute();
           
        } catch (SQLException ex) {
            Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
            if(conn != null)
            {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null)
            {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        }
         
         
         public static List<Student> findByRollNoorFullname(String searchValue)
    {
        Connection conn = null ;
        Statement statement = null ;
        List<Student> studentList = new ArrayList<>();
        try {
            // Lấy tất cả sinh viên
            
            // B1 : mở connection tới dtb

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanaging?serverTimezone=UTC" , "root" , "");
        
            
            // B2 : Query
            
            
            String sql = "select * from student where rollno like '%"+ searchValue + "%'  or fullname like '%" + searchValue + "%' ";
            statement = conn.prepareStatement(sql);
            
            
            // Lấy dữ liệu trả về :
            
            ResultSet resultSet = statement.executeQuery(sql);
            
            // Lấy bảng ghi dữ liệu resultset -> lưu vào biến
            
            while (resultSet.next())
            {
                Student std = new Student(
                resultSet.getInt("rollno"),
                resultSet.getString("fullname"),
                resultSet.getString("gender"),
                resultSet.getString("email"),
                resultSet.getString("address")
                );
                
                studentList.add(std);
            }
            
            
            
        } catch (SQLException ex) {
            Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
            if(conn != null)
            {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null)
            {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmodify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return studentList;
    }
    
    
}
package javaimportexportxml;


import java.util.ArrayList;
import java.util.List;
import javaimportexportxmlandjson.Student;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;




/*
 * 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.
 */

/**
 *
 * @author abc
 */
public class StudentHandler extends DefaultHandler {
    
    
    List<Student> studentlist = new ArrayList<>();
    Student currentStudent = null;
    boolean isRollno = false , isFullname = false , isGender = false , isAddress = false , isEmail = false;
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
      if (qName.equalsIgnoreCase("student"))
      {
          currentStudent = new Student();
      }
      else if(qName.equalsIgnoreCase("rollno"))
      {
          isRollno = true;
      }
      else if(qName.equalsIgnoreCase("fullname"))
      {
          isFullname = true;
      }
      else if(qName.equalsIgnoreCase("gender"))
      {
          isGender = true;
      }
      else if (qName.equalsIgnoreCase("email"))
      {
          isEmail = true;
      }
      else if(qName.equalsIgnoreCase("address"))
      {
          isAddress = true;
      }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
       if(qName.equalsIgnoreCase("student"))
       {
           studentlist.add(currentStudent);
           currentStudent = null;
       }
       else if(qName.equalsIgnoreCase("rollno"))
       {
           isRollno = false;
       }
       else if(qName.equalsIgnoreCase("fullname"))
       {
           isFullname = false;
       }
       else if(qName.equalsIgnoreCase("gender"))
       {
           isGender = false;
       }
       else if(qName.equalsIgnoreCase("email"))
       {
           isEmail = false;
       }
       else if(qName.equalsIgnoreCase("address"))
       {
           isAddress = false;
       }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String value = new String(ch, start, length);
        if (isRollno)
        {
            currentStudent.setRollno(length);
        }
        else if(isFullname)
        {
            currentStudent.setFullname(value);
        }
        else if(isGender)
        {
            currentStudent.setGender(value);
        }
        else if(isAddress)
        {
            currentStudent.setAddress(value);
        }
    }

    public List<Student> getStudentlist() {
        return studentlist;
    }

    
}



Trương Công Vinh [T1907A]
Trương Công Vinh

2020-04-23 13:14:26



/*
 * 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 Test_XML_JSON_mySQL;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.json.JSONArray;
import org.xml.sax.SAXException;

/**
 *
 * @author DELL
 */
public class studentJFrame extends javax.swing.JFrame {

    ArrayList<Student> studentList;
    DefaultTableModel tableModel;

    /**
     * Creates new form studentJFrame
     */
    public studentJFrame() {
        studentList = new ArrayList<>();
        initComponents();
    }

    public void showdata() {
        studentList = studentModify.findAll();
        for (Student student : studentList) {
            tableModel.addRow(new Object[]{student.getRollno(),
                student.getHoten(),
                student.getGioitinh(),
                student.getEmail(),
                student.getDiachi()
            });
        }
    }

    public void reset() {
        txtdiachi.setText("");
        txtemail.setText("");
        txtrollno.setText("");
        txtten.setText("");
    }

    /**
     * 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">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtrollno = new javax.swing.JTextField();
        txtten = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtemail = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtdiachi = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        cbgioitinh = new javax.swing.JComboBox<>();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Rollno : ");

        jLabel2.setText("Ho Ten : ");

        jLabel3.setText("Gioi Tinh : ");

        jLabel4.setText("email : ");

        jLabel5.setText("Dia Chi : ");

        cbgioitinh.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Nam", "Nu", " " }));

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

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

        jButton4.setText("import JSON");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("export JSON");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

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

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

        jButton6.setText("Save");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(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(34, 34, 34)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtdiachi, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtemail, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtrollno, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(1, 1, 1)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbgioitinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtten, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(74, 74, 74)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(49, 49, 49))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtrollno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton2)
                            .addComponent(jButton3))
                        .addGap(15, 15, 15)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cbgioitinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .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))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtdiachi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton7)
                    .addComponent(jButton6))
                .addContainerGap(32, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(34, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        String rollno = txtrollno.getText();
        if (rollno.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Rollno is empty ?");
        } else {
            Student std = studentModify.find(rollno);

            if (std == null) {
                JOptionPane.showMessageDialog(rootPane, "Not found any student by rollno");
                return;
            }
            txtten.setText(std.getHoten());
            txtdiachi.setText(std.getDiachi());
            txtemail.setText(std.getEmail());
            cbgioitinh.setSelectedItem(std.getGioitinh());
            JOptionPane.showMessageDialog(rootPane, "Search success !!");
        }
    }                                        

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        reset();
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
          ArrayList<Student> XMLlist = new ArrayList<>();
          XMLlist = studentModify.importXML();
          Connection connection = null;
          
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentTestTotal?serverTimezone=UTC", "root", "");
            for (Student student : XMLlist) {
                studentModify.save(student);
            }
        } catch (SQLException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
          

    }                                        

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Student std = new Student(txtrollno.getText(), txtten.getText(), cbgioitinh.getSelectedItem().toString(), txtemail.getText(), txtdiachi.getText());

        studentModify.save(std);
        JOptionPane.showMessageDialog(rootPane, "save success !!");
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        FileReader reader = null;
        try {
            
            // TODO add your handling code here:
            File file = null;
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                file = fileChooser.getSelectedFile();
                // load from file
            }
            if (file == null) {
                JOptionPane.showMessageDialog(rootPane, "Not file selected");
                return;
            }
            java.lang.reflect.Type classOfT = new TypeToken<ArrayList<Student>>(){}.getType();
            reader = new FileReader(file);
            Gson gson = new Gson();
            ArrayList<Student> list = gson.fromJson(reader, classOfT);

            for (Student std : list) {
                studentModify.save(std);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        reset();
    }                                        

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        File file = null;
        
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
          file = fileChooser.getSelectedFile();
          // save to file
        }
        if(file == null) {
            JOptionPane.showMessageDialog(rootPane, "Not save");
            return;
        }
        
        FileOutputStream fos = null;
        try {
            // TODO add your handling code here:
            List<Student> studentList = searchStudents();
            //convert List to JSON file
            JSONArray arr = new JSONArray(studentList);
//            System.out.println(arr.toString());

            fos = new FileOutputStream(file);
            byte[] b = arr.toString().getBytes();
            
            fos.write(b);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export JSON success!!!");
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        File file = null;
        
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
          file = fileChooser.getSelectedFile();
          // save to file
        }
        if(file == null) {
            JOptionPane.showMessageDialog(rootPane, "Not save");
            return;
        }
        
        List<Student> studentList = searchStudents();
        
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);

            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<students>";
            fos.write(str.getBytes());
            
            for (Student std : studentList) {
                fos.write(std.getXMLString().getBytes());
            }
            
            str = "</students>";
            fos.write(str.getBytes());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export XML success!!!");
    }                                        
private List<Student> searchStudents() {
        String searchValue = JOptionPane.showInputDialog("Enter search value");
        
        List<Student> studentList = null;
        
        if(searchValue.isEmpty()) {
            studentList = studentModify.findAll();
        } else {
            studentList = studentModify.findBYhotenORrollno(searchValue);
        }
        return studentList;
    }
    /**
     * @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(studentJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(studentJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(studentJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(studentJFrame.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 studentJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox<String> cbgioitinh;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    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.JTextField txtdiachi;
    private javax.swing.JTextField txtemail;
    private javax.swing.JTextField txtrollno;
    private javax.swing.JTextField txtten;
    // End of variables declaration                   

}



/*
 * 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 Test_XML_JSON_mySQL;

/**
 *
 * @author DELL
 */
public class Student {
    String rollno,hoten,gioitinh,email,diachi;

    public Student() {
    }

    public Student(String rollno, String hoten, String gioitinh, String email, String diachi) {
        this.rollno = rollno;
        this.hoten = hoten;
        this.gioitinh = gioitinh;
        this.email = email;
        this.diachi = diachi;
    }

    public String getRollno() {
        return rollno;
    }

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

    public String getHoten() {
        return hoten;
    }

    public void setHoten(String hoten) {
        this.hoten = hoten;
    }

    public String getGioitinh() {
        return gioitinh;
    }

    public void setGioitinh(String gioitinh) {
        this.gioitinh = gioitinh;
    }

    public String getEmail() {
        return email;
    }

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

    public String getDiachi() {
        return diachi;
    }

    public void setDiachi(String diachi) {
        this.diachi = diachi;
    }

    @Override
    public String toString() {
        return "Student{" + "rollno=" + rollno + ", hoten=" + hoten + ", gioitinh=" + gioitinh + ", email=" + email + ", diachi=" + diachi + '}';
    }
    public String getXMLString() {
        return "<student>\n" +
"		<rollno>"+rollno+"</rollno>\n" +
"		<fullname>"+hoten+"</fullname>\n" +
"		<email>"+email+"</email>\n" +
"		<gender>"+gioitinh+"</gender>\n" +
"		<address>"+diachi+"</address>\n" +
"	</student>";
    }
}



/*
 * 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 Test_XML_JSON_mySQL;

import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author DELL
 */
public class studentHandler extends DefaultHandler{
    ArrayList<Student> stdList;
    
    Student currentStudent = null;
    boolean isRollno = false , isHoten =false , isGoitinh = false , isEmail = false , isDiachi = false;

    public studentHandler() {
        stdList = new ArrayList<>();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if(qName.equalsIgnoreCase("student")) {
            currentStudent = new Student();
        } else if(qName.equalsIgnoreCase("rollNo")) {
            isRollno = true;
        } else if(qName.equalsIgnoreCase("hoten")) {
            isHoten = true;
        } else if(qName.equalsIgnoreCase("gioitinh")) {
            isGoitinh = true;
        } else if(qName.equalsIgnoreCase("email")) {
            isEmail = true;
        }else if(qName.equalsIgnoreCase("diachi")) {
            isDiachi = true;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(qName.equalsIgnoreCase("student")) {
            stdList.add(currentStudent);
            currentStudent = null;
        } else if(qName.equalsIgnoreCase("rollNo")) {
            isRollno = false;
        } else if(qName.equalsIgnoreCase("hoten")) {
            isHoten = false;
        } else if(qName.equalsIgnoreCase("gioitinh")) {
            isGoitinh = false;
        } else if(qName.equalsIgnoreCase("email")) {
            isEmail = false;
        }else if(qName.equalsIgnoreCase("diachi")) {
            isDiachi = false;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
         String value = new String(ch, start, length);
         if (currentStudent != null) {
             if (isRollno) {
                 currentStudent.setRollno(value);
             }else if (isDiachi) {
                 currentStudent.setDiachi(value);
             }else if (isRollno) {
                 currentStudent.setEmail(value);
             }else if (isRollno) {
                 currentStudent.setGioitinh(value);
             }else if (isRollno) {
                 currentStudent.setHoten(value);
             }
        }
    }

    public ArrayList<Student> getStdList() {
        return stdList;
    }
    
    
}



/*
 * 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 Test_XML_JSON_mySQL;

import java.io.FileInputStream;
import java.io.IOException;
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.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author DELL
 */
public class studentModify {

    public static ArrayList<Student> findAll() {
        ArrayList<Student> list = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentTestTotal?serverTimezone=UTC", "root", "");
            statement = connection.createStatement();
            String sql = "Select * from student ";

            ResultSet resultset = statement.executeQuery(sql);
            while (resultset.next()) {
                Student std = new Student(resultset.getString("rollno"),
                        resultset.getString("hoten"),
                        resultset.getString("gioitinh"),
                        resultset.getString("email"),
                        resultset.getString("diachi"));
                list.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);
                }
            }
        }

        return list;
    }
    public static ArrayList<Student> findBYhotenORrollno(String key) {
        ArrayList<Student> list = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentTestTotal?serverTimezone=UTC", "root", "");
            
            String sql = "select * from student where rollno like '%"+key+"%' or fullname like '%"+key+"%'";
            statement = connection.createStatement();

            ResultSet resultset = statement.executeQuery(sql);
            while (resultset.next()) {
                Student std = new Student(resultset.getString("rollno"),
                        resultset.getString("hoten"),
                        resultset.getString("gioitinh"),
                        resultset.getString("email"),
                        resultset.getString("diachi"));
                list.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);
                }
            }
        }

        return list;
    }

    private static void insert(Student std) {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentTestTotal?serverTimezone=UTC", "root", "");

            String sql = "insert into student values (?,?,?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, std.getRollno());
            statement.setString(2, std.getHoten());
            statement.setString(3, std.getGioitinh());
            statement.setString(4, std.getEmail());
             statement.setString(5, std.getDiachi());
             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);
                  }
            }
        }
    }
    private static void update(Student std){
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentTestTotal?serverTimezone=UTC", "root", "");

            String sql = "update student set hoten = ? , gioitinh = ? , email = ? , diachi = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, std.getHoten());
            statement.setString(2, std.getGioitinh());
            statement.setString(3, std.getEmail());
             statement.setString(4, std.getDiachi());
             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);
                  }
            }
        }
    }
    public static Student find(String rollno){
       Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentTestTotal?serverTimezone=UTC", "root", "");
            
            //query
            String sql = "select * from student where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, rollno);
            
            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next()) {
                Student std = new Student(resultSet.getString("rollno"), 
                        resultSet.getString("hoten"), 
                        resultSet.getString("gioitinh"), 
                        resultSet.getString("email"), 
                        resultSet.getString("diachi"));
                return 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(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(studentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }
    public static void save(Student std){
        Student stdFind =  find(std.getRollno());
        if (stdFind != null) {
            update(std);
        }else{
            insert(std);
        }
    }
    public static void delete(String rollno){
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentTestTotal?serverTimezone=UTC", "root", "");

            String sql = "delete from stident where rollno = ?";
            
            statement = connection.prepareStatement(sql);
            statement.setString(1, rollno );
            
             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);
                  }
            }
        }
    }
    public static ArrayList<Student> importXML() {
        ArrayList<Student> studentList  = new ArrayList<>();
        
        FileInputStream fis = null;
        try {
            // TODO add your handling code here:
            fis = new FileInputStream("d://XML/student_export_xmL.xml");
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();

            studentHandler handler = new studentHandler();

            parser.parse(fis, handler);

            studentList = handler.getStdList();

            

        } catch (SAXException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }  finally {

            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(studentJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        }
        return studentList;
    }
    
}



Trần Mạnh Dũng [T1907A]
Trần Mạnh Dũng

2020-04-23 11:40:45

Phần Import XML em điền thông tin rồi import thì nó báo lỗi ở 

               for (Student student : studentList) {

                tableModel.addRow(new Object[]{

                student.getName(), student.getGender(),

                    student.getRollno(), student.getEmail(),

                    student.getAddress()

                });

      Nhưng code ở ở trên không báo lỗi nên em không biết sửa kiểu gì thầy ạ


/*
 * 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 quanlisinhvien;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.json.JSONArray;
import org.xml.sax.SAXException;
/**
 *
 * @author admin
 */
public class StudentFrame extends javax.swing.JFrame {
    List<Student> studentList = new ArrayList<>();
    DefaultTableModel tableModel;
    /**
     * Creates new form StudentFrame
     */
    public StudentFrame() {
        initComponents();
        tableModel = (DefaultTableModel) tblStudent.getModel();
    }

    /**
     * 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">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        txtRollno = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        txtAddress = new javax.swing.JTextField();
        cbGender = new javax.swing.JComboBox<>();
        btnSearch = new javax.swing.JButton();
        btnImportXML = new javax.swing.JButton();
        btnImportJSON = new javax.swing.JButton();
        btnExportXML = new javax.swing.JButton();
        btnExportJSON = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblStudent = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input Student Detail's Information"));

        jLabel1.setText("Name:");

        jLabel2.setText("Gender:");

        jLabel3.setText("Roll No:");

        jLabel4.setText("Email:");

        jLabel5.setText("Address:");

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

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

        btnImportXML.setText("Import XML");
        btnImportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportXMLActionPerformed(evt);
            }
        });

        btnImportJSON.setText("Import JSON");
        btnImportJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportJSONActionPerformed(evt);
            }
        });

        btnExportXML.setText("Export XML");
        btnExportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportXMLActionPerformed(evt);
            }
        });

        btnExportJSON.setText("Export JSON");
        btnExportJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportJSONActionPerformed(evt);
            }
        });

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(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()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(68, 68, 68)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(63, 63, 63)
                        .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(txtName, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
                        .addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtRollno)
                        .addComponent(txtEmail)
                        .addComponent(txtAddress)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnImportJSON, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnExportJSON, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnExportXML, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnImportXML, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(43, 43, 43))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSearch))
                .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)
                    .addComponent(btnImportXML))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtRollno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnImportJSON))
                .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)
                    .addComponent(btnExportXML))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnExportJSON)))
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnReset))
                .addContainerGap(26, Short.MAX_VALUE))
        );

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

            },
            new String [] {
                "Roll No", "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);

        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)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        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, 130, 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:
        txtRollno.setText("");
        txtName.setText("");
        txtEmail.setText("");
        txtAddress.setText("");
        cbGender.setSelectedIndex(0);
    }                                        

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        String rollno = txtRollno.getText();
        String name = txtName.getText();
        String email = txtEmail.getText();
        String address = txtAddress.getText();
        String gender = cbGender.getSelectedItem().toString();
        
        if (rollno.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Roll no is empty");
        } else if (name.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Name is empty");
        } else if (email.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Email is empty");
        } else if (address.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Address is empty");
        }
        Student std = new Student(name, rollno, gender, email, address);
        
        StudentModify.save(std);
        btnResetActionPerformed(null);
        JOptionPane.showMessageDialog(rootPane, "Add Success");
    }                                      

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        String rollno = txtRollno.getText();
        if (rollno.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Roll no is empty");
            return;
        }
        Student std = StudentModify.find(rollno);
        if(std == null){
            JOptionPane.showMessageDialog(rootPane, "Not found any student by roll no"); 
            return;
        }
        txtName.setText(std.getName());
        txtEmail.setText(std.getEmail());
        txtAddress.setText(std.getAddress());
        cbGender.setSelectedItem(std.getGender());
    }                                         

    private void btnExportXMLActionPerformed(java.awt.event.ActionEvent evt) {                                             

         File file = null;
        
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
          file = fileChooser.getSelectedFile();
        }
        if(file == null) {
            JOptionPane.showMessageDialog(rootPane, "Not Add");
            return;
        }
        
        List<Student> studentList = searchStudents();
        
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);

            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<student_list>";
            fos.write(str.getBytes());
            
            for (Student std : studentList) {
                fos.write(std.getXMLString().getBytes());
            }
            
            str = "</student_list>";
            fos.write(str.getBytes());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export XML Success");
    }                                            

    private void btnExportJSONActionPerformed(java.awt.event.ActionEvent evt) {                                              
       File file = null;
        
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
          file = fileChooser.getSelectedFile();
          // save to file
        }
        if(file == null) {
            JOptionPane.showMessageDialog(rootPane, "Not Add");
            return;
        }
        
        FileOutputStream fos = null;
        try {
            // TODO add your handling code here:
            List<Student> studentList = searchStudents();
            //convert List to JSON file
            JSONArray arr = new JSONArray(studentList);
//            System.out.println(arr.toString());

            fos = new FileOutputStream(file);
            byte[] b = arr.toString().getBytes();
            
            fos.write(b);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export JSON Success!!!");
    }                                            
    private List<Student> searchStudents() {
        String searchValue = JOptionPane.showInputDialog("Enter Roll No Want Export");
        
        List<Student> studentList = null;
        
        if(searchValue.isEmpty()) {
            studentList = StudentModify.findAll();
        } else {
            studentList = StudentModify.findByRollnoOrName(searchValue);
        }
        return studentList;
    }                                             

    private void btnImportJSONActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
        FileReader reader = null;
        try {
         
            File file = null;
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                file = fileChooser.getSelectedFile();
            
            }   if(file == null) {
                JOptionPane.showMessageDialog(rootPane, "Not file selected");
                return;
            }
            java.lang.reflect.Type classOfT = new TypeToken<ArrayList<Student>>(){}.getType();
            reader = new FileReader(file);
            Gson gson = new Gson();
            ArrayList<Student> list = gson.fromJson(reader, classOfT);
            
            for (Student std : list) {
                StudentModify.save(std);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        JOptionPane.showMessageDialog(rootPane, "Import JSON Success");
    }                                             

    private void btnImportXMLActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        FileInputStream fis = null;
        try {
            // TODO add your handling code here:
            fis = new FileInputStream("QuanlisinhvienXML.xml");
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            
            StudentHander handler = new StudentHander();
            
            parser.parse(fis, handler);
            
            studentList = handler.getStudentList();
            
            tableModel.setRowCount(0);
            for (Student student : studentList) {
                tableModel.addRow(new Object[]{
                student.getName(), student.getGender(),
                    student.getRollno(), student.getEmail(),
                    student.getAddress()
                });
            }
            
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Import Success");
    }                                            

    /**
     * @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 btnAdd;
    private javax.swing.JButton btnExportJSON;
    private javax.swing.JButton btnExportXML;
    private javax.swing.JButton btnImportJSON;
    private javax.swing.JButton btnImportXML;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSearch;
    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 txtAddress;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtRollno;
    // End of variables declaration                   
}



/*
 * 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 quanlisinhvien;

/**
 *
 * @author admin
 */
public class Student {
    String name, rollno, gender, email, address;

    public Student() {
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRollno() {
        return rollno;
    }

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

    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 getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", rollno=" + rollno + ", gender=" + gender + ", email=" + email + ", address=" + address + '}';
    }
    public void display(){
        System.out.println(this);
    }
    public String getXMLString(){
        return "<student>\n"
                + "       <name>" + name + "</name>\n"
                + "        <gender>" + gender + "</gender>\n"
                + "        <rollno>" + rollno + "</rollno>\n"
                + "        <email>" + email + "</email>\n"
                + "        <address>" + address + "</address> \n"
                + "   </student>";
    }
}



/*
 * 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 quanlisinhvien;


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;



/**
 *
 * @author admin
 */
public class StudentModify {
    public static List<Student> findAll(){
        Connection conn = null;
        Statement statement = null;
        List<Student> studentList = new ArrayList<>(); 
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetail?serverTimezone=UTC", "root", "");
            statement = conn.createStatement();
            String sql = "select * from student";
            
            ResultSet resultSet = statement.executeQuery(sql);
            while(resultSet.next()){
                Student std = new Student(resultSet.getString("rollno"),
                        resultSet.getString("name"),
                        resultSet.getString("gender"),
                        resultSet.getString("email"),
                        resultSet.getString("address"));
                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(conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return studentList;
    }
    
    private static void insert(Student std){
        Connection conn = null;
        PreparedStatement statement = null;
        List<Student> studentList = new ArrayList<>(); 
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetail?serverTimezone=UTC", "root", "");
            String sql = "insert into student(rollno, name, gender, email, address)"
                    +"values (?, ?, ?, ?, ?)";
            statement = conn.prepareCall(sql);
            statement.setString(1, std.getRollno());
            statement.setString(2, std.getName());
            statement.setString(3, std.getGender());
            statement.setString(4, std.getEmail());
            statement.setString(5, std.getAddress());
            
            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(conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    private static void update(Student std){
        Connection conn = null;
        PreparedStatement statement = null;
        List<Student> studentList = new ArrayList<>(); 
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetail?serverTimezone=UTC", "root", "");
            String sql = "update student set name = ?, gender = ?, email = ?, address = ?"
                    + "where rollno = ?";
            statement = conn.prepareCall(sql);
            statement.setString(1, std.getName());
            statement.setString(2, std.getGender());
            statement.setString(3, std.getEmail());
            statement.setString(4, std.getAddress());
            statement.setString(5, std.getRollno());
            
            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(conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    public static List<Student> findByRollnoOrName(String searchValue) {
        Connection conn = null;
        Statement statement = null;
        List<Student> studentList = new ArrayList<>();
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetail?serverTimezone=UTC", "root", "");
            
            //query
            String sql = "select * from student where rollno like '%"+searchValue+"%' or name like '%"+searchValue+"%'";
            statement = conn.createStatement();
            
            ResultSet resultSet = statement.executeQuery(sql);
            
            while(resultSet.next()) {
                Student std = new Student(resultSet.getString("name"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("rollno"), 
                        resultSet.getString("email"), 
                        resultSet.getString("address"));
                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(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        return studentList;
    }
    public static void save(Student std){
        Student stdFind = find(std.getRollno());
        
        if(stdFind == null){
            insert(std);
        }else{
            update(std);
        }
        
    }
    public static Student find(String rollno){
        Connection conn = null;
        PreparedStatement statement = null;

        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetail?serverTimezone=UTC", "root", "");
            
            String sql = "select * from student where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, rollno);
            
            ResultSet resultSet = statement.executeQuery();
            while(resultSet.next()){
                Student std = new Student(resultSet.getString("name"),
                        resultSet.getString("gender"),
                        resultSet.getString("rollno"),
                        resultSet.getString("email"),
                        resultSet.getString("address"));
                return 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(conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }
    public static void delete(String rollno){
        Connection conn = null;
        PreparedStatement statement = null;

        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetail?serverTimezone=UTC", "root", "");
            
            String sql = "delete from student where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, rollno);
            
            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(conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}



/*
 * 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 quanlisinhvien;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.events.StartElement;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author admin
 */
public class StudentHander extends DefaultHandler {

    List<Student> studentList = new ArrayList<>();
    Student currentStudent = null;
    
    boolean isRollno = false;
    boolean isName = false;
    boolean isGender = false;
    boolean isEmail = false;
    boolean isAddress = false;
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equalsIgnoreCase("student")) {
            studentList.add(currentStudent);
            currentStudent = new Student();
        } else if (qName.equalsIgnoreCase("name")) {
            isName = true;
        } else if (qName.equalsIgnoreCase("gender")) {
            isGender = true;
        } else if (qName.equalsIgnoreCase("rollno")) {
            isRollno = true;
        } else if (qName.equalsIgnoreCase("email")) {
            isEmail = true;
        } else if (qName.equalsIgnoreCase("address")) {
            isAddress = true;
        }
    }
    
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equalsIgnoreCase("student")) {
            studentList.add(currentStudent);
            currentStudent = null;
        } else if (qName.equalsIgnoreCase("name")) {
            isName = false;
        } else if (qName.equalsIgnoreCase("gender")) {
            isGender = false;
        } else if (qName.equalsIgnoreCase("rollno")) {
            isRollno = false;
        } else if (qName.equalsIgnoreCase("email")) {
            isEmail = false;
        } else if (qName.equalsIgnoreCase("address")) {
            isAddress = false;
        }
    }
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String value = new String(ch, start, length);
        if (isName) {
            currentStudent.setName(value);
        } else if (isRollno) {
            currentStudent.setRollno(value);
        } else if (isGender) {
            currentStudent.setGender(value);
        } else if (isEmail) {
            currentStudent.setEmail(value);
        } else if (isAddress) {
            currentStudent.setAddress(value);
        }
        
    }

    public List<Student> getStudentList() {
        return studentList;
    }
    
}



Đường Thanh Bình [T1907A]
Đường Thanh Bình

2020-04-23 04:01:03



/*
 * 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 Test;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.json.JSONArray;
/**
 *
 * @author Administrator
 */
public class StudentJFrame extends javax.swing.JFrame {
    

    /**
     * Creates new form StudentJFrame
     */
    public StudentJFrame() {
        initComponents();
    }

    /**
     * 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">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtRollNo = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtAddress = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();
        cbGender = new javax.swing.JComboBox<>();
        btnSearch = new javax.swing.JButton();
        ImportJSON = new javax.swing.JButton();
        btnImportXML = new javax.swing.JButton();
        btnExportXML = new javax.swing.JButton();
        btnExportJSON = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("quanlysinhvien"));

        txtName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNameActionPerformed(evt);
            }
        });

        jLabel2.setText("Ho Ten");

        jLabel3.setText("Gioi Tinh");

        jLabel4.setText("Roll No");

        txtRollNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtRollNoActionPerformed(evt);
            }
        });

        jLabel5.setText("Email");

        txtAddress.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtAddressActionPerformed(evt);
            }
        });

        jLabel6.setText("Dia Chi");

        txtEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtEmailActionPerformed(evt);
            }
        });

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

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

        ImportJSON.setText("Import JSON");
        ImportJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ImportJSONActionPerformed(evt);
            }
        });

        btnImportXML.setText("Import XML");
        btnImportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportXMLActionPerformed(evt);
            }
        });

        btnExportXML.setText("Export XML");
        btnExportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportXMLActionPerformed(evt);
            }
        });

        btnExportJSON.setText("Export JSON");
        btnExportJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportJSONActionPerformed(evt);
            }
        });

        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);
            }
        });

        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(32, 32, 32)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addGap(58, 58, 58)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(98, 98, 98))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(btnSave)
                                .addGap(29, 29, 29)
                                .addComponent(btnReset)
                                .addGap(175, 175, 175))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtRollNo, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(ImportJSON, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnExportXML, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnImportXML, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnExportJSON, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(749, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)
                        .addComponent(btnSearch))
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(12, 12, 12)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtRollNo, 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(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(jLabel6)
                            .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnImportXML)
                        .addGap(18, 18, 18)
                        .addComponent(ImportJSON)
                        .addGap(18, 18, 18)
                        .addComponent(btnExportXML)
                        .addGap(18, 18, 18)
                        .addComponent(btnExportJSON)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSave)
                    .addComponent(btnReset))
                .addContainerGap(177, Short.MAX_VALUE))
        );

        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()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void txtNameActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void txtRollNoActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    private void txtAddressActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void txtEmailActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void ImportJSONActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
         FileReader reader = null;
        try {
            // TODO add your handling code here:
            File file = null;
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                file = fileChooser.getSelectedFile();
                // load from file
            }   if(file == null) {
                JOptionPane.showMessageDialog(rootPane, "Not file selected");
                return;
            }
            java.lang.reflect.Type classOfT = new TypeToken<ArrayList<Student>>(){}.getType();
            reader = new FileReader(file);
            Gson gson = new Gson();
            ArrayList<Student> list = gson.fromJson(reader, classOfT);
            
            for (Student std : list) {
                StudentModify.save(std);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        JOptionPane.showMessageDialog(rootPane, "Import JSON success!!!");
    }                                          

    private void btnExportXMLActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
         File file = null;
        
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
          file = fileChooser.getSelectedFile();
          // save to file
        }
        if(file == null) {
            JOptionPane.showMessageDialog(rootPane, "Not save");
            return;
        }
        
        List<Student> studentList = searchStudent();
        
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);

            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<students>";
            fos.write(str.getBytes());
            
            for (Student std : studentList) {
                fos.write(std.getXMLString().getBytes());
            }
            
            str = "</students>";
            fos.write(str.getBytes());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export XML success!!!");
    }                                            

    private void btnExportJSONActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
         File file = null;
        
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
          file = fileChooser.getSelectedFile();
          // save to file
        }
        if(file == null) {
            JOptionPane.showMessageDialog(rootPane, "Not save");
            return;
        }
        
        FileOutputStream fos = null;
        try {
            // TODO add your handling code here:
            List<Student> studentList = searchStudent();
            //convert List to JSON file
            JSONArray arr = new JSONArray(studentList);
//            System.out.println(arr.toString());

            fos = new FileOutputStream(file);
            byte[] b = arr.toString().getBytes();
            
            fos.write(b);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export JSON success!!!");
    }                                             

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        String rollno = txtRollNo.getText();
        String fullname = txtName.getText();
        String gender = cbGender.getSelectedItem().toString();
        String address = txtAddress.getText();
        String email = txtEmail.getText();
        
        if(rollno.isEmpty() || fullname.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "No empty rollno or fullname");
            return;
        }
        
        Student std = new Student(rollno, fullname, gender, email, address);
        
        StudentModify.save(std);
        
        btnResetActionPerformed(null);
        
        JOptionPane.showMessageDialog(rootPane, "Save success!!!");
    }                                       

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        txtRollNo.setText("");
        txtName.setText("");
        txtEmail.setText("");
        txtAddress.setText("");
        cbGender.setSelectedIndex(0);
    }                                        

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        String rollno = txtRollNo.getText();
        if(rollno.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "No empty rollno");
            return;
        }
        Student std = StudentModify.find(rollno);
        if(std == null) {
            JOptionPane.showMessageDialog(rootPane, "Not found any student by rollno");
            return;
        }
        txtName.setText(std.getFullName());
        txtEmail.setText(std.getEmail());
        txtAddress.setText(std.getAddress());
        cbGender.setSelectedItem(std.getGender());
    }                                         

    private void btnImportXMLActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        
    }                                            

    private List<Student> searchStudent() {
        String searchValue = JOptionPane.showInputDialog("Enter search value");
        
        List<Student> studentList = null;
        
        if(searchValue.isEmpty()) {
            studentList = StudentModify.findAll();
        } else {
            studentList = StudentModify.findByRollnoOrFullname(searchValue);
        }
        return studentList;
    /**
     * @param args the command line arguments
     */
    
    public static void main(String args[]) {
         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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }
        /* 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(StudentJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StudentJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StudentJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StudentJFrame.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 StudentJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton ImportJSON;
    private javax.swing.JButton btnExportJSON;
    private javax.swing.JButton btnExportXML;
    private javax.swing.JButton btnImportXML;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    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.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtAddress;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtRollNo;
    // End of variables declaration                   




/*
 * 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 Test;
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;
/**
 *
 * @author Administrator
 */
public class StudentModify {
     public static List<Student> findAll() {
        Connection conn = null;
        Statement statement = null;
        List<Student> studentList = new ArrayList<>();
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            //query
            statement = conn.createStatement();
            String sql = "select * from students";
            
            ResultSet resultSet = statement.executeQuery(sql);
            
            while(resultSet.next()) {
                Student std = new Student(resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("email"), 
                        resultSet.getString("address"));
                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(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        return studentList;
    }
    
    public static List<Student> findByRollnoOrFullname(String searchValue) {
        Connection conn = null;
        Statement statement = null;
        List<Student> studentList = new ArrayList<>();
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            //query
            String sql = "select * from students where rollno like '%"+searchValue+"%' or fullname like '%"+searchValue+"%'";
            statement = conn.createStatement();
            
            ResultSet resultSet = statement.executeQuery(sql);
            
            while(resultSet.next()) {
                Student std = new Student(resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("email"), 
                        resultSet.getString("address"));
                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(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        return studentList;
    }
    
    private static void insert(Student std) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            String sql = "insert into students(rollno, fullname, gender, email, address)"
                    + "values (?, ?, ?, ?, ?)";
            statement = conn.prepareStatement(sql);
            statement.setString(1, std.getRollNo());
            statement.setString(2, std.getFullName());
            statement.setString(3, std.getGender());
            statement.setString(4, std.getEmail());
            statement.setString(5, std.getAddress());
            
            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(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    private static void update(Student std) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            String sql = "update students set fullname = ?, gender = ?, email = ?, address = ?"
                    + " where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, std.getFullName());
            statement.setString(2, std.getGender());
            statement.setString(3, std.getEmail());
            statement.setString(4, std.getAddress());
            statement.setString(5, std.getRollNo());
            
            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(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public static void save(Student std) {
        Student stdFind = find(std.getRollNo());
        
        if(stdFind == null) {
            insert(std);
        } else {
            update(std);
        }
    }
    
    public static Student find(String rollno) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            //query
            String sql = "select * from students where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, rollno);
            
            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next()) {
                Student std = new Student(resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("email"), 
                        resultSet.getString("address"));
                return 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(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }
    
    public static void delete(String rollno) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            //query
            String sql = "delete from students where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, rollno);
            
            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(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

   
}



/*
 * 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 Test;

/**
 *
 * @author Administrator
 */
public class Student {
    String RollNo,FullName,Gender,Email,Address;

    public Student() {
    }

    public Student(String rollno, String FullName, String Gender, String Email, String Address) {
        this.RollNo = RollNo;
        this.FullName = FullName;
        this.Gender = Gender;
        this.Email = Email;
        this.Address = Address;
    }

    Student(String string) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    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 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 getAddress() {
        return Address;
    }

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

    @Override
    public String toString() {
        return "Student{" + "RollNo=" + RollNo + ", FullName=" + FullName + ", Gender=" + Gender + ", Email=" + Email + ", Address=" + Address + '}';
    }
    
    public void display(){
        System.out.println(this);
    }
    
    public String getXMLString(){
        return "<student>\n" + 
                "<rollno>"+RollNo+"</rollno>\n"+
                "<fullname>"+FullName+"</rollno\n"+
                "<email>"+Email+"</email>\n"+
                "<gender>"+Gender+"</gender>\n"+
                "<address>"+Address+"</address>\n"+
                "</student>";
    }
}