IMG-LOGO
Trang Chủ Java Advanced Quản lý sinh viên + XML + JSON + MySQL bằng Java
×

Lý Thuyết

01. exception + debug + package - lập trình Java Nâng Cao 02. Tìm hiểu collections, Sets, Maps và Generic - lập trình java nâng cao 03. Hướng dẫn đọc ghi file FileInputStream, FileOutputStream, ObjectInputStream trong java - lập trình java nâng cao BT01. chua bai tap ObjectOutputStream & ObjectInputStream - lập trình java nâng cao 04. Tìm hiểu Thread - Phân 1 - lập trình java nâng cao 05. Tìm hiểu Thread trong Java - Phần 2 - lập trình java nâng cao 06. Tìm hiểu Thread trong java - Phần 3- lập trình java nâng cao BT02. Chữa bài tập Thread - Lập trình Java 07. Đông bộ thread + wait notify + synchronized + Lập trình Java - lập trình java nâng cao 08. Giải thích synchronized + Lap trinh Java nang cao BT03. Chữa bài tập hiển thị đồng bộ Thông tin tên & địa chỉ trên 2 thread khác nhau - java- lập trình java nâng cao BT04. chữa bài tập quản lý bán vé máy bay - java nâng cao 09. Kết nối MySQL trong java swing JDBC trong java - lập trình java nâng cao 10. Kết nối CSDL bằng java swing phần 2 - lập trình java nâng cao 11. Design Pattern lập trình java nâng cao - lập trình java nâng cao BT05. Bài tập quản lý sở thú - Phần 1 - lập trình java nâng cao BT06. Bài tập quản lý sở thú - Phần 2 - lập trình java nâng cao BT07. Hướng dẫn chữa bài tập JDBC - quản lý sinh viên - lập trình java nâng cao BT08. Quản lý sản phẩm + 2 bảng danh mục & sản phẩm + Lập trình java nâng cao BT09. Ứng dụng quản lý sinh viên - nhập dữ liệu từ file json - java nâng cao 12. Chuyển đổi json sang object java (sử dụng thư viện gson) - lập trình java nâng cao BT10. Lập trình java nâng cao - chữa bài tập tổng quát 181

Bài Tập

Java Advanced- BT18 Quản lý thông tin sinh & lưu file (ObjectOutputStream & ObjectInputStream) Java Advanced- Bài tập ôn luyện String, StringBuilder, StringBuffer Java Advanced- Chương trình quản lý sinh viên bằng HashMap File - Quản lý thông tin sinh viên Bài tập nén File & giải nén File & Liệt kê files trong 1 thư mục - winrar - winzip Bài tập quản lý sách & lưu thông tin trên Files Thread thực hiện in ngẫu nhiên các số nguyên và ký tự MultiThread - Sinh số ngẫu nhiên và hiển thị bình phương số ngẫu nhiên & Synchronized trong Java MultiThread - Synchronized trong Java - Đồng bộ 3 threads - Sinh số ngẫu nhiên, bình phương, và chia hết Tao tác dữ liệu lên Shared Object sử dụng MultiThreading trong java Sử dụng MultiThreading sinh ký tự a-zA-Z trong java Bài tập quản lý sinh viên bằng Java Swing + File Bài Tập Quản Lý Sinh Viên - CSDL - Java Swing Tạo tài liệu XML/JSON - quản lý lớp học Viết chương trình phân tích tài liệu XML thông tin cá nhân bằng Java Quản lý thông tin cá nhân Profile bằng java - import + export XML File Tạo JSON file & đọc nội dung JSON file thông tin cá nhân bằng Java Tìm mảng a2 kết hợp mảng a1 tạo mảng a là các phân tử liên tiếp nhau Phần mềm quản lý sinh viên MySQL + Java - Chương trình quản lý sinh viên MySQL + Java - Lập Trình Java Bài tập - Viết chương trình quản lý sản phẩm - quản lý tin tức - quản lý bán hàng - Lập trình Java

Examination & Test

Examination & Test >> Quản lý bán hàng + java console Examination & Test >> Quản lý bán hàng + java swing Examination & Test + Quản lý sinh viên + kiểm tra 60 phút Quản lý sinh viên + XML + JSON + MySQL bằng Java Mini Project - Phân tích dự án + Phát triển phần mềm ATM Quản lý sách bằng Java - Lập trình Java [Share Code] Tìm hiểu về Generic & FileInputStream & FileOutputStream - Lập trình java nâng cao. [Examination] XML/JSON - T2008A

Source Code Chia Sẻ

Share Code- Lession 1 - Java Advanced - T1907A Share Code- Lession 2 - Generic + FileInputStream + FileOutputStream - T1907A Share Code- File - ObjectInputStream - ObjectOutputStream - T1907A Share Code - Hướng dẫn chữa bài quản lý sinh vien + file Share Code - Bài giảng nén file & giải nén File - T1907A Share Code - Thread trong java + Thread.Sleep + join trong java Share Code - Thread - MultiThread - Synchonized wait notify notifyAll trong java Share Code - Sử dụng MultiThreading sinh ký tự a-zA-Z trong java Share Code - MultiThread - Synchronized trong Java - Đồng bộ 3 threads - Sinh số ngẫu nhiên, bình phương, và chia hết Share Code - Hướng dẫn chữa bài >> Bài tập ôn luyện tổng hợp File, OOP, Thread trong java Share Code - Hướng dẫn học java swing Phần 1 - T1907A Share Code - Kết nối CSDL + Swing trong java phần 1 - T1907A Share Code - Hướng dẫn giải bài tập quản lý sinh viên + CSDL + Java Swing Share Code - XML - Hướng dẫn viết tài liệu XML Share Code - Hướng dẫn phân tích tài liệu XML quản lý lớp học bằng Java Share Code - Hướng dẫn tạo dự án quản lý sinh viên + import + export XML File Share Code - JSON - Thông tin lớp học bằng Java Share Code - Hướng dẫn sử dụng gson - quản lý lớp học bằng Java Share Code - Quản lý sinh viên + XML + JSON + MySQL bằng Java Share Code - Tìm hiểu Exception + Throw + Try Catch + Package Share Code - Tìm hiểu Collections & Generic trong Java Share Code - Hướng dẫn dọc ghi dữ liệu trên File - C1907L Share Code - Hướng dẫn tạo dự án WinRar, WinZip, 7Zip toàn tập bằng Java Hướng dẫn tìm hiểu đệ quy qua bài Fibonaci - Recursion Fibonaci - Java Phân chia mảng số nguyên thành 2 phần + chắc + lẻ [Share Code] MultiThread - Sinh số ngẫu nhiên và hiển thị bình phương số ngẫu nhiên & Synchronized trong Java [Share Code] Tìm hiểu Thread trong Java, MultiThreading trong Java, Lập trình Java [Share Code] Sử dụng MultiThreading sinh ký tự a-zA-Z trong java - Lập trình Java - Thread trong Java [Share Code] CRUD - Chương trình quản lý sinh viên - Test CSDL - jdbc mysql driver - Lập Trình Java [Share Code] Localization - Lập Trình Đa Ngôn Ngữ - Lập Trình Java - Java Advanced [Share Code] Java Console - Chương trình quản lý sinh viên thêm, sửa, xóa, tìm kiếm, hiển thị Java + MySQL [Share Code] Tìm hiểu về Thread - MultiThreading - Synchronized Trong Java - Lập trình java [Share Code] MultiThread - Sinh số ngẫu nhiên và hiển thị bình phương số ngẫu nhiên & Synchronized trong Java - Ôn Tập ADF [Share Code] MultiThread - Synchronized trong Java - Đồng bộ 3 threads - Sinh số ngẫu nhiên, bình phương, và chia hết - Class C1907L [Share Code] Tìm hiểu Thread trong Java, MultiThreading trong Java, Lập trình Java - Lớp C1907L [Share Code] Hướng dẫn tìm hiểu MySQL trong Java - Quản lý user trong Java + MySQL [Share Code] Tìm hiểu về Exception - List & Map & ArrayList & Vector - Lập trình Java nâng cao [Share Code] Tìm hiểu ObjectInputStream + ObjectOutputStream - Thread - Lập trình Java [Share Code] Tìm hiểu về Thread - Synchronized Trong Java - Lập trình Java nâng cao [Share Code] Tìm hiểu về thiết kế Swing Form - Lập trình Java Nâng Cao [Share Code] Tìm hiểu về Localization - Quản lý sinh viên và kết nối cơ sở dữ liệu - Lập trình Jva nâng cao [Share Code] Mô tả thông tin cá nhân bằng XML - Lập trình XML/JSON [Khoá học Java nâng cao] Chương trình quản lý thư viện + XML [Share Code] gson trong Java - Vi dụ json trong java - Bài tập quản lý sản phẩm + json trong Java




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

by GokiSoft.com - 14:57 12/04/2021 4,958 Lượt Xem

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)

Theo dõi cập nhật nội dung học trên Youtube & Facebook


Bình luận



Chia sẻ từ lớp học

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

Ngày viết: 23:52 13/04/2021


#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]

Ngày viết: 23:27 13/04/2021



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

Ngày viết: 23:27 13/04/2021



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

Ngày viết: 23:26 13/04/2021



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

Ngày viết: 23:25 13/04/2021



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


Phân Loại Bài Viết

Danh Sách Bài Học

Đã sao chép!!!