IMG-LOGO
×

Tài Liệu Học

Khoá học lập trình Java Core nâng cao

Exception & Collection

[Video] Tìm hiểu exception + debug + package - lập trình Java Nâng Cao [Video] Tìm hiểu collections, Sets, Maps và Generic - lập trình java nâng cao [Video] Chương trình quản lý sinh viên bằng HashMap - Java Advanced

File

[Video] Hướng dẫn đọc ghi file FileInputStream, FileOutputStream, ObjectInputStream trong java - lập trình java nâng cao [Video] Bài tập quản lý sách & lưu thông tin trên Files [Video] File - Quản lý thông tin sinh viên [Video] Quản lý thông tin sinh & lưu object file - Java nâng cao [Video] Viết ứng dụng WinRar | WinZip | 7Zip bằng Java - Nén file Java & giải nén file Java - Khoá học Java [Video] Bài tập quản lý bán vé máy bay - java nâng cao

Thread

[Video] Phân tích quản lý ứng dụng trong HĐH (Window, Mac, Linux)-Phân tích Game đa luồng Java [Video] Tìm hiểu Thread - Đồng bộ Thread - lập trình java nâng cao - Bổ sung thêm lớp học mới. [Video] Giải thích synchronized + Lap trinh Java nang cao [Video] Thread thực hiện in ngẫu nhiên các số nguyên và ký tự - Phần 1 [Video] Thread thực hiện in ngẫu nhiên các số nguyên và ký tự & Đông bộ thread + wait notify + synchronized + Java nâng cao - Phần 2 [Video] Synchronized 2 Thread - Bài tập mảng tên + địa chỉ - Java nâng cao [Video] Bài tập ôn luyện tổng hợp File, OOP, Thread trong java [Video] Sử dụng MultiThreading sinh ký tự a-zA-Z trong java

CSDL

[Video] Kết nối MySQL trong java swing JDBC trong java - lập trình java nâng cao [Video] Kết nối CSDL bằng java swing phần 1 - lập trình java nâng cao [Video] Kết nối CSDL bằng java swing phần 2 - lập trình java nâng cao [Video] Chương trình quản lý thư viện Java + XML Java + CSDL Java- SQL Java [Video] 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 [Video] Bài Tập Quản Lý Sinh Viên - CSDL - Java Swing [Video] 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 [Video] Chức năng register & login + CSDL - Lập trình Java nâng cao - Phần 1 [Video] Hướng dẫn sử dụng Persistence Java - Kết nối database Java - MySQL Java nâng cao

Design Pattern & Đa Ngôn Ngữ

[Video] Design Pattern lập trình java nâng cao - lập trình java nâng cao

XML & JSON & CSDL

[Video] C1 > Chương trình quản lý sinh viên Java + Import/Export JSON + File - Lập Trình Java [Video] C2 > Chương trình quản lý sinh viên Java + Import/Export JSON + File - Lập Trình Java

Ôn Tập Tổng Quát & Exmination

[Video] Bài tập - Chường trình quản lý sở thú - Lập trình Java - Lập trình Java nâng cao - Phần 1 [Video] Bài tập - Chường trình quản lý sở thú - Lập trình Java - Lập trình Java nâng cao - Phần 2




Trang Chủ Java Advanced Bài tập - Nhập thông tin sinh viên từ JSON vào CSDL - Lập trình Java nâng cao.

Bài tập - Nhập thông tin sinh viên từ JSON vào CSDL - Lập trình Java nâng cao.

by GokiSoft.com - 14:52 26/09/2021 1,311 Lượt Xem

Tạo CSDL đặt tên là: quanlysinhvien gồm 1 bảng students gồm các bảng (id tự tăng, rollno, fullname, phone, email, address, status (giá trị là: PENDING, LEARNING, DROPOUT), father_name, father_phone, mother_name, mother_phone

Tạo file json gồm ít nhất 5 bản ghi chứa các thông tin sinh viên như trên

Viết tools: gồm các button

Import JSON to CSDL -> Thực hiện nhập dữ liệu sv vào database theo rollno (Nếu ko tồn tại thêm mới, nếu tồn tại update)

Export CSDL to XML -> Xuất thông tin sinh viên ra file XML

Bình luận



Phản Hồi Bởi:

(1) Đào Mạnh Dũng [C2010L]

Chia sẻ từ lớp học

Đào Mạnh Dũng [C2010L]

Ngày viết: 10:10 26/09/2021


#Main.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 pkg2429;

import com.formdev.flatlaf.FlatDarkLaf;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JFileChooser;
import org.json.JSONObject;
import org.json.XML;

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

    /**
     * Creates new form Main
     */
    public Main() {
        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() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
        jButton1.setText("Import JSON to CSDL");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
        jButton2.setText("Export CSDL to XML");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        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(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(52, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(103, Short.MAX_VALUE))
        );

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

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        Gson gson = new Gson();
        String json = "{\"studentsList\":" + gson.toJson(new studentsList(db.studentsModify.SELECT())) + "}";
        System.out.println(json);
        JSONObject obj = new JSONObject(json);
        String xml_data = XML.toString(obj);
        System.out.println(xml_data);
        Utility.FileUtf8.SaveFile(xml_data, "quanlysinhvien.xml");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser file = new JFileChooser("./");

        if (file.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

            Gson gson = new Gson();
            String json = Utility.FileUtf8.ReadFile(file.getSelectedFile().toPath().toString());
            
            HashMap<Integer, students> list = getMap(db.studentsModify.SELECT());

            studentsList studentlist = gson.fromJson(json, studentsList.class);
            for (int i = 0; i < studentlist.student.size(); i++) {
                students get = studentlist.student.get(i);
                if (list.get(get.id)==null) {
                    db.studentsModify.INSERT(get);
                }else{
                    db.studentsModify.UPDATE(get);
                }
            }
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        FlatDarkLaf.setup();

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration//GEN-END:variables

    private HashMap<Integer, students> getMap(ArrayList<students> SELECT) {
        HashMap<Integer, students> tmp = new HashMap();
        for (int i = 0; i < SELECT.size(); i++) {
            students get = SELECT.get(i);
            tmp.put(get.id, get);
        }
        return tmp;
    }
}


Đào Mạnh Dũng [C2010L]

Ngày viết: 22:03 25/09/2021


#FileUtf8.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 Utility;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Đào Dũng
 */
public class FileUtf8 {

    public static String ReadFile(String path) {
        StringBuilder result = new StringBuilder();
        FileReader Reader = null;
        BufferedReader Buffered = null;
        try {
            Reader = new FileReader(path);
            Buffered = new BufferedReader(Reader);

            String line;
            while ((line = Buffered.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException ex) {
            Logger.getLogger(FileUtf8.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (Reader != null) {
                try {
                    Reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(FileUtf8.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (Buffered != null) {
                try {
                    Buffered.close();
                } catch (IOException ex) {
                    Logger.getLogger(FileUtf8.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return result.toString();
    }

    public static void SaveFile(String content, String path) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path, false);
            fos.write(content.getBytes());
            System.out.println("Save File " + path + " success!");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileUtf8.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileUtf8.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(FileUtf8.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


#Main.form


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

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

  <Layout>
    <DimensionLayout dim="0">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" alignment="0" attributes="0">
              <EmptySpace min="-2" pref="51" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="0" attributes="0">
                  <Component id="jButton2" min="-2" pref="297" max="-2" attributes="0"/>
                  <Component id="jButton1" min="-2" pref="297" max="-2" attributes="0"/>
              </Group>
              <EmptySpace pref="52" 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="53" max="-2" attributes="0"/>
              <Component id="jButton1" min="-2" pref="63" max="-2" attributes="0"/>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Component id="jButton2" min="-2" pref="63" max="-2" attributes="0"/>
              <EmptySpace pref="103" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Component class="javax.swing.JButton" name="jButton1">
      <Properties>
        <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
          <Font name="Segoe UI" size="18" style="1"/>
        </Property>
        <Property name="text" type="java.lang.String" value="Import JSON to CSDL"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JButton" name="jButton2">
      <Properties>
        <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
          <Font name="Segoe UI" size="18" style="1"/>
        </Property>
        <Property name="text" type="java.lang.String" value="Export CSDL to XML"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton2ActionPerformed"/>
      </Events>
    </Component>
  </SubComponents>
</Form>


#Main.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 pkg2429;

import com.formdev.flatlaf.FlatDarkLaf;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JFileChooser;
import org.json.JSONObject;
import org.json.XML;

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

    /**
     * Creates new form Main
     */
    public Main() {
        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() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
        jButton1.setText("Import JSON to CSDL");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
        jButton2.setText("Export CSDL to XML");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        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(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(52, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(103, Short.MAX_VALUE))
        );

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

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        Gson gson = new Gson();
        String json = "{\"studentsList\":" + gson.toJson(new studentsList(db.studentsModify.SELECT())) + "}";
        System.out.println(json);
        JSONObject obj = new JSONObject(json);
        String xml_data = XML.toString(obj);
        System.out.println(xml_data);
        Utility.FileUtf8.SaveFile(xml_data, "quanlysinhvien.xml");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser file = new JFileChooser("./");

        if (file.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

            Gson gson = new Gson();
            String json = Utility.FileUtf8.ReadFile(file.getSelectedFile().toPath().toString());
            
            HashMap<Integer, students> list = getMap(db.studentsModify.SELECT());

            studentsList studentlist = gson.fromJson(json, studentsList.class);
            for (int i = 0; i < studentlist.student.size(); i++) {
                students get = studentlist.student.get(i);
                System.out.println(get);
                if (list.get(get.id)!=null) {
                    db.studentsModify.INSERT(get);
                }else{
                    db.studentsModify.UPDATE(get);
                }
            }
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        FlatDarkLaf.setup();

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration//GEN-END:variables

    private HashMap<Integer, students> getMap(ArrayList<students> SELECT) {
        HashMap<Integer, students> tmp = new HashMap();
        for (int i = 0; i < SELECT.size(); i++) {
            students get = SELECT.get(i);
            tmp.put(get.id, get);
        }
        return tmp;
    }
}


#Status.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 pkg2429;

/**
 *
 * @author inter
 */
public enum Status {
    PENDING, LEARNING, DROPOUT;
}


#students.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 pkg2429;

/**
 *
 * @author inter
 */
public class students {

    int id;
    Status status;
    String rollno, fullname, phone, email, address, father_name, father_phone, mother_name, mother_phone;

    public students() {
    }

    public students(int id, Status status, String rollno, String fullname, String phone, String email, String address, String father_name, String father_phone, String mother_name, String mother_phone) {
        this.id = id;
        this.status = status;
        this.rollno = rollno;
        this.fullname = fullname;
        this.phone = phone;
        this.email = email;
        this.address = address;
        this.father_name = father_name;
        this.father_phone = father_phone;
        this.mother_name = mother_name;
        this.mother_phone = mother_phone;
    }

    public int getId() {
        return id;
    }

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

    public String getStatus() {
        return status.toString();
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    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 getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    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 String getFather_name() {
        return father_name;
    }

    public void setFather_name(String father_name) {
        this.father_name = father_name;
    }

    public String getFather_phone() {
        return father_phone;
    }

    public void setFather_phone(String father_phone) {
        this.father_phone = father_phone;
    }

    public String getMother_name() {
        return mother_name;
    }

    public void setMother_name(String mother_name) {
        this.mother_name = mother_name;
    }

    public String getMother_phone() {
        return mother_phone;
    }

    public void setMother_phone(String mother_phone) {
        this.mother_phone = mother_phone;
    }

    @Override
    public String toString() {
        return "students{" + "id=" + id + ", status=" + status + ", rollno=" + rollno + ", fullname=" + fullname + ", phone=" + phone + ", email=" + email + ", address=" + address + ", father_name=" + father_name + ", father_phone=" + father_phone + ", mother_name=" + mother_name + ", mother_phone=" + mother_phone + '}';
    }

}


#studentsList.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 pkg2429;

import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;

/**
 *
 * @author inter
 */
public class studentsList {
    
    @SerializedName("student")
    ArrayList<students> student;

    public studentsList(ArrayList<students> student) {
        this.student = student;
    }
    
}


#Config.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 db;

/**
 *
 * @author inter
 */
public interface Config {
    String DB_URL = "jdbc:mysql://localhost:3306/quanlysinhvien";
    String USERNAME = "root";
    String PASSWORD = "";
}


#Modify.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 db;

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

/**
 * @Modify ObjectClass
 * @author inter
 */
class Modify {

    static Connection conn = null;
    static PreparedStatement statement = null;

    static void connection() {
        try {
            conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
        } catch (SQLException ex) {
            Logger.getLogger(Modify.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static void close() {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(Modify.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                Logger.getLogger(Modify.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

/*
public class ObjectClassModify extends Modify {
    
    public static ArrayList<ObjectClass> SELECT() {
        ArrayList<ObjectClass> data = new ArrayList<>();
        connection();

        String sql = null;
        sql = "SELECT";
        try {

            statement = conn.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                data.add(new ObjectClass(
                        resultSet.getString("")
                        
                ));
            }
        } catch (SQLException ex) {
            Logger.getLogger(ObjectClassModify.class.getName()).log(Level.SEVERE, null, ex);
        }
        close();
        return data;
    }

    public static ArrayList<ObjectClass> SELECT(String like) {
        ArrayList<ObjectClass> data = new ArrayList<>();
        connection();

        String sql = null;
        sql = "SELECT";
        sql += "WHERE Something LIKE \"%" + like + "%\";";
        try {

            statement = conn.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                data.add(new ObjectClass(
                        resultSet.getString("")
                        
                ));
            }
        } catch (SQLException ex) {
            Logger.getLogger(ObjectClassModify.class.getName()).log(Level.SEVERE, null, ex);
        }
        close();
        return data;
    }

    public static void INSERT(ObjectClass item) {
        connection();
        String sql = null;
        sql = "INSERT";
        try {
            statement = conn.prepareStatement(sql);

            statement.setString(1, item.get);
            statement.setString(2, item.get);
            statement.setString(3, item.get);
            statement.setString(4, item.get);
            statement.setString(5, item.get);
            statement.setString(6, item.get);
            statement.setString(7, item.get);
            statement.setString(8, item.get);

            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(ObjectClassModify.class.getName()).log(Level.SEVERE, null, ex);
        }
        close();
    }

    public static void UPDATE(ObjectClass item) {
        connection();
        String sql = null;
        sql = "UPDATE";
        try {
            statement = conn.prepareStatement(sql);

            statement.INSERT

            statement.setString(8, item.get);

            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(ObjectClassModify.class.getName()).log(Level.SEVERE, null, ex);
        }
        close();
    }

    public static void DELETE(ObjectClass item) {
        connection();
        String sql = null;
        sql = "DELETE";
        try {
            statement = conn.prepareStatement(sql);

            statement.setString(1, item.get);

            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(ObjectClassModify.class.getName()).log(Level.SEVERE, null, ex);
        }
        close();
    }
}    
*/

}


#studentsModify.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 db;

import java.util.ArrayList;
import pkg2429.students;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import pkg2429.Status;

/**
 *
 * @author inter
 */
public class studentsModify extends Modify {

    public static ArrayList<students> SELECT() {
        ArrayList<students> data = new ArrayList<>();
        connection();

        String sql = null;
        sql = "SELECT * FROM `students`";
        try {

            statement = conn.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                data.add(new students(
                        resultSet.getInt("id"),
                        status(resultSet.getString("status")),
                        resultSet.getString("rollno"),
                        resultSet.getString("fullname"),
                        resultSet.getString("phone"),
                        resultSet.getString("email"),
                        resultSet.getString("address"),
                        resultSet.getString("father_name"),
                        resultSet.getString("father_phone"),
                        resultSet.getString("mother_name"),
                        resultSet.getString("mother_phone")
                ));
            }
        } catch (SQLException ex) {
            Logger.getLogger(studentsModify.class.getName()).log(Level.SEVERE, null, ex);
        }
        close();
        return data;
    }
    
    public static void UPDATE(students item) {
        connection();
        String sql = null;
        sql = "UPDATE `students` SET `status` = ?, `rollno` = ?, `fullname` = ?, `phone` = ?, `email` = ?, `address` = ?, `father_name` = ?, `father_phone` = ?, `mother_name` = ?, `mother_phone` = ? WHERE `students`.`id` = ?;";
        try {
            statement = conn.prepareStatement(sql);

            statement.setString(1, item.getStatus());
            statement.setString(2, item.getRollno());
            statement.setString(3, item.getFullname());
            statement.setString(4, item.getPhone());
            statement.setString(5, item.getEmail());
            statement.setString(6, item.getAddress());
            statement.setString(7, item.getFather_name());
            statement.setString(8, item.getFather_phone());
            statement.setString(9, item.getMother_name());
            statement.setString(10, item.getMother_phone());

            statement.setInt(11, item.getId());

            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(studentsModify.class.getName()).log(Level.SEVERE, null, ex);
        }
        close();
    }
    
    public static void INSERT(students item) {
        connection();
        String sql = null;
        sql = "INSERT INTO `students` (`status`, `rollno`, `fullname`, `phone`, `email`, `address`, `father_name`, `father_phone`, `mother_name`, `mother_phone`) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?);";
        try {
            statement = conn.prepareStatement(sql);

            statement.setString(1, item.getStatus());
            statement.setString(2, item.getRollno());
            statement.setString(3, item.getFullname());
            statement.setString(4, item.getPhone());
            statement.setString(5, item.getEmail());
            statement.setString(6, item.getAddress());
            statement.setString(7, item.getFather_name());
            statement.setString(8, item.getFather_phone());
            statement.setString(9, item.getMother_name());
            statement.setString(10, item.getMother_phone());

            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(studentsModify.class.getName()).log(Level.SEVERE, null, ex);
        }
        close();
    }


    private static Status status(String status) {
        switch (status) {
            case "PENDING" -> {
                return Status.PENDING;
            }
            case "LEARNING" -> {
                return Status.LEARNING;
            }
            case "DROPOUT" -> {
                return Status.DROPOUT;
            }
        }
        return null;
    }

}


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

Tài Liệu Tham Khảo

Đã sao chép!!!