Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Java

The document contains code for a student management application that allows users to add, view, and save student data to a file and database. It defines classes for the student data model, DAO for database operations, and GUI for the user interface. The main method initializes the student list, loads existing data from file to list, and displays the student list view window.

Uploaded by

Lynn
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Java

The document contains code for a student management application that allows users to add, view, and save student data to a file and database. It defines classes for the student data model, DAO for database operations, and GUI for the user interface. The main method initializes the student list, loads existing data from file to list, and displays the student list view window.

Uploaded by

Lynn
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

import DAO.

StudentDAO;
import GUI.ViewStudentList;
import Model.Student;

import java.awt.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {


public static List<Student> studentList;
public static Scanner scanner;
public static Scanner in;
public static File file;
public static FileWriter fileWriter;
public static PrintWriter printWriter;

public static void main(String[] args) {


studentList = new ArrayList<>();
scanner = new Scanner(System.in);
file = new File("sv.dat");
taoDanhSachSinhVien();
}

public static void taoDanhSachSinhVien() {


while (true) {
System.out.println("\nBan co muon nhap sinh vien? (yes/no)");
var nhap = scanner.nextLine();
if (nhap.equals("yes")) {
System.out.println("\n****Nhap sinh vien****\n");
} else if (nhap.equals("no")) {
break;
} else {
System.out.println("\nChi duoc nhap yes hoac no. Xin hay thu lai!\n");
}
System.out.println("Nhap MSSV:");
var mssv = scanner.nextLine();
System.out.println("Nhap ten sinh vien: ");
var ten = scanner.nextLine();
System.out.println("Nhap lop:");
var lop = scanner.nextLine();
var student = new Student(mssv, ten, lop);
studentList.add(student);
}
try {
writeFileByPrintWriter();
// writeFileByFileWriter();
readFile();
} catch (Exception e) {
throw new RuntimeException(e);
}
EventQueue.invokeLater(() -> new ViewStudentList(studentList));
}

public static void writeFileByPrintWriter() throws NullPointerException, IOException {


printWriter = new PrintWriter(new FileOutputStream(file, true));
for (var student : studentList) {
printWriter.println(writeData(student));
}
printWriter.close();
}

public static void writeFileByFileWriter() throws NullPointerException, IOException {


fileWriter = new FileWriter(file, true);
for (var student : studentList) {
fileWriter.write(writeData(student));
fileWriter.write(System.getProperty("line.separator"));
}
fileWriter.close();
}

private static String writeData(Student student) {


return (student.getMssv() + "|" + student.getTen() + "|" + student.getLop());
}

public static void readFile() throws IOException {


in = new Scanner(file, StandardCharsets.UTF_8);
studentList.clear();
while (in.hasNextLine()) {
var student = readData();
studentList.add(student);
}
saveStudentListToDatabase(studentList);
}

private static Student readData() {


var line = in.nextLine();
var tokens = line.split("\\|");
var mssv = tokens[0];
var ten = tokens[1];
var lop = tokens[2];
return new Student(mssv, ten, lop);
}

private static void saveStudentListToDatabase(List<Student> studentList) {


for (var student : studentList) {
StudentDAO.insert(student);
}
}
}

package Model;

public class Student {


String mssv;
String ten;
String lop;

public Student(String mssv, String ten, String lop) {


this.mssv = mssv;
this.ten = ten;
this.lop = lop;
}

@Override
public String toString() {
return "Model.SinhVien{" +
"mssv='" + mssv + '\'' +
", ten='" + ten + '\'' +
", lop='" + lop + '\'' +
'}';
}
public String getMssv() {
return mssv;
}

public void setMssv(String mssv) {


this.mssv = mssv;
}

public String getTen() {


return ten;
}

public void setTen(String ten) {


this.ten = ten;
}

public String getLop() {


return lop;
}

public void setLop(String lop) {


this.lop = lop;
}
}

package JDBCHelper;

import javax.swing.*;
import java.sql.*;

public class DatabaseConnection {


private static final String dbms = "mysql";
private static final String hostname = "localhost";
private static final String port = "3306";
private static final String schemas = "dbStudent";
private static final String username = "root";
private static final String password = "123456";
private static final String url = "jdbc:"
+ dbms
+ "://"
+ hostname
+ ":"
+ port
+ "/"
+ schemas;

private static Connection instance;

static {
try {
instance = DatabaseConnection.getConnection();
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(
null,
"Không thể kết nối đến cơ sở dữ liệu. Hãy chạy lại ứng dụng!",
"Lỗi",
JOptionPane.ERROR_MESSAGE
);
e.printStackTrace();
System.exit(1);
}
}

private DatabaseConnection() {
}

private static Connection getConnection() throws ClassNotFoundException, SQLException {


Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(
url,
username,
password
);
}

public static Connection getConnectionInstance() {


return instance;
}

public static void main(String[] args) {


Connection con;
Statement statement;
ResultSet resultSet;
try {
con = DatabaseConnection.getConnectionInstance();
statement = con.createStatement();
resultSet = statement.executeQuery("select * from student");
while (resultSet.next()) {
System.out.println(resultSet.getString("mssv"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

package GUI;

import Model.Student;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.util.List;

public class ViewStudentList extends JFrame {


private final List<Student> studentList;
private JTextField textFieldStudent;
private JTable tableStudent;
private JPanel panelStudent;
private DefaultTableModel columnModel;
private DefaultTableModel rowModel;
private TableRowSorter<TableModel> rowSorter;
public ViewStudentList(List<Student> studentList) {
this.studentList = studentList;
initComponents();
addEvents();
this.setTitle("Danh Sách Sinh Viên");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(panelStudent);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
fillDataToTable();
}

private void initComponents() {


columnModel = new DefaultTableModel(
new Object[][]{},
new String[]{"MSSV", "Họ và tên", "Lớp"}
);
tableStudent.setModel(columnModel);
rowModel = (DefaultTableModel) tableStudent.getModel();
rowSorter = new TableRowSorter<>(rowModel);
tableStudent.setRowSorter(rowSorter);
}

private void addEvents() {


textFieldStudent.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
var text = textFieldStudent.getText().strip();
if (text.length() != 0) {
rowSorter.setRowFilter(RowFilter.regexFilter(text, 1));
} else {
rowSorter.setRowFilter(null);
}
}

@Override
public void removeUpdate(DocumentEvent e) {
var text = textFieldStudent.getText().strip();
if (text.length() != 0) {
rowSorter.setRowFilter(RowFilter.regexFilter(text, 1));
} else {
rowSorter.setRowFilter(null);
}
}

@Override
public void changedUpdate(DocumentEvent e) {

}
});
}

private void fillDataToTable() {


rowModel.setRowCount(0);
for (var student : studentList) {
rowModel.addRow(new Object[]{
student.getMssv(),
student.getTen(),
student.getLop()
});
}
}
}

package DAO;

import JDBCHelper.DatabaseConnection;
import Model.Student;

import java.sql.SQLException;

public class StudentDAO {


public static void insert(Student student) {
var query = "insert into student(mssv,ten,lop) values(?,?,?)";
try (var ps = DatabaseConnection.getConnectionInstance().prepareStatement(query)) {
ps.setString(1, student.getMssv());
ps.setString(2, student.getTen());
ps.setString(3, student.getLop());
ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

Bai khac ve database de tham khao

public class ConnectJDBC {

private String hostName = "localhost:8082";

private String dbName = "my_database";

private String username = "root";

private String password = "123";

private String connectionURL = "jdbc:mysql://"+hostName+"/"+dbName;

public Connection connect(){

//Tạo đối tượng Connection

Connection conn = null;

try {

conn = DriverManager.getConnection(connectionURL, username, password);

System.out.println("Kết nối thành công");


} catch (SQLException e) {

e.printStackTrace();

return conn;

Lay toan bo thong tin user


public class Main {

public static void main(String[] args) {

ConnectJDBC connectJDBC = new ConnectJDBC();

Connection conn = connectJDBC.connect();

String query = "SELECT * FROM users WHERE username = ?";

PreparedStatement pstm = null;

try {

//Tạo đối tượng Statement

pstm = conn.prepareStatement(query);

//gán các giá trị vào tham số

pstm.setString(1, "ngoc");

//Thực thi truy vấn và trả về đối tượng ResultSet

ResultSet rs = pstm.executeQuery();

//Duyệt kết quả trả về


while (rs.next()){

int id = rs.getInt("id");

String username = rs.getString("username");

String password = rs.getString("password");

String email = rs.getString("email");

System.out.println(id + " - " + username + " - " + password + " - " + email);

//Đóng kết nối

conn.close();

} catch (SQLException e) {

e.printStackTrace();

Them du lieu moi


Tham số được đại diện bởi dấu ?, bạn phải cung cấp giá trị cho tất cả các tham số trước khi thực
hiện câu lệnh SQL. Mỗi tham số sẽ được đánh dấu bằng số thứ tự, tham số đầu tiên có vị trí là 1,
kế tiếp là 2,…

public class Main {

public static void main(String[] args) {

ConnectJDBC connectJDBC = new ConnectJDBC();

Connection conn = connectJDBC.connect();

String query = "INSERT INTO users(id, username, password, email) " +

"VALUES (null, ?,?,?)";


PreparedStatement pstm = null;

try {

pstm = conn.prepareStatement(query);

pstm.setString(1, "hung");

pstm.setString(2, "123456789");

pstm.setString(3, "hung@gmail.com");

//Khi thực hiện các lệnh insert/update/delete sử dụng executeUpdate(), nó sẽ trả về số hàng
bị tác động

int row = pstm.executeUpdate();

if(row != 0){

System.out.println("Thêm thành công " + row);

//Đóng kết nối

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}
Lớp này để lưu thông tin cho mỗi sinh viên.
package vn.viettuts;
 
import java.io.Serializable;
 
/**
 * Student class
 *
 * @author viettuts.vn
 */
public class Student implements Serializable {
    private int id;
    private String name;
    private byte age;
    private String address;
    /* điểm trung bình của sinh viên */
    private float gpa;
 
    public Student() {
    }
 
    public Student(int id, String name, byte age,
            String address, float gpa) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
        this.gpa = gpa;
    }
 
    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 byte getAge() {
        return age;
    }
 
    public void setAge(byte age) {
        this.age = age;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
    public float getGpa() {
        return gpa;
    }
 
    public void setGpa(float gpa) {
        this.gpa = gpa;
    }
}

package vn.viettuts;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
 
/**
 * StudentDao class
 *
 * @author viettuts.vn
 */
public class StudentDao {
    private static final String STUDENT_FILE_NAME = "student.txt";
 
    /**
     * save list student to file
     *
     * @param studentList: list student to save
     */
    public void write(List<Student> studentList) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream(new File(STUDENT_FILE_NAME));
            oos = new ObjectOutputStream(fos);
            oos.writeObject(studentList);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeStream(fos);
            closeStream(oos);
        }
    }
 
    /**
     * read list student from file
     *
     * @return list student
     */
    public List<Student> read() {
        List<Student> studentList = new ArrayList<>();
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(new File(STUDENT_FILE_NAME));
            ois = new ObjectInputStream(fis);
            studentList = (List<Student>) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            closeStream(fis);
            closeStream(ois);
        }
        return studentList;
    }
 
    /**
     * close input stream
     *
     * @param is: input stream
     */
    private void closeStream(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * close output stream
     *
     * @param os: output stream
     */
    private void closeStream(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
// sắp xếp sinh viên tăng dần theo điểm trung bình

package vn.viettuts;
 
import java.util.Comparator;
 
/**
 * SortStudentByGPA class
 *
 * @author viettuts.vn
 */
public class SortStudentByGPA implements Comparator<Student> {
    @Override
    public int compare(Student student1, Student student2) {
        if (student1.getGpa() > student2.getGpa()) {
            return 1;
        }
        return -1;
    }
}

// sap xep sinh vien tang dan theo ten

package vn.viettuts;
 
import java.util.Comparator;
 
/**
 * SortStudentByName class
 *
 * @author viettuts.vn
 */
public class SortStudentByName implements Comparator<Student> {
    @Override
    public int compare(Student student1, Student student2) {
        return student1.getName().compareTo(student2.getName());
    }
}

//tao lop student manager


package vn.viettuts;
 
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
 
/**
 * StudentManager class
 *
 * @author viettuts.vn
 */
public class StudentManager {
    public static Scanner scanner = new Scanner(System.in);
    private List<Student> studentList;
    private StudentDao studentDao;
     
    /**
     * init StudentDao object and
     * read list student when init StudentManager object
     */   
    public StudentManager() {
        studentDao = new StudentDao();
        studentList = studentDao.read();
    }
 
    /**
     * add student to studentList
     *
     * @param student
     */
    public void add() {
        int id = (studentList.size() > 0) ? (studentList.size() + 1) : 1;
        System.out.println("student id = " + id);
        String name = inputName();
        byte age = inputAge();
        String address = inputAddress();
        float gpa = inputGpa();
        Student student = new Student(id, name, age, address, gpa);
        studentList.add(student);
        studentDao.write(studentList);
    }
 
    /**
     * edit student by id
     *
     * @param id
     */
    public void edit(int id) {
        boolean isExisted = false;
        int size = studentList.size();
        for (int i = 0; i < size; i++) {
            if (studentList.get(i).getId() == id) {
                isExisted = true;
                studentList.get(i).setName(inputName());
                studentList.get(i).setAge(inputAge());
                studentList.get(i).setAddress(inputAddress());
                studentList.get(i).setGpa(inputGpa());
                break;
            }
        }
        if (!isExisted) {
            System.out.printf("id = %d not existed.\n", id);
        } else {
            studentDao.write(studentList);
        }
    }
 
    /**
     * delete student by id
     *
     * @param id: student id
     */
    public void delete(int id) {
        Student student = null;
        int size = studentList.size();
        for (int i = 0; i < size; i++) {
            if (studentList.get(i).getId() == id) {
                student = studentList.get(i);
                break;
            }
        }
        if (student != null) {
            studentList.remove(student);
            studentDao.write(studentList);
        } else {
            System.out.printf("id = %d not existed.\n", id);
        }
    }
 
    /**
     * sort student by name
     */
    public void sortStudentByName() {
        Collections.sort(studentList, new SortStudentByName());
    }
 
    /**
     * sort student by id
     */
    public void sortStudentByGPA() {
        Collections.sort(studentList, new SortStudentByGPA());
    }
 
    /**
     * show list student to screen
     */
    public void show() {
        for (Student student : studentList) {
            System.out.format("%5d | ", student.getId());
            System.out.format("%20s | ", student.getName());
            System.out.format("%5d | ", student.getAge());
            System.out.format("%20s | ", student.getAddress());
            System.out.format("%10.1f%n", student.getGpa());
        }
    }
 
    /**
     * input student id
     *
     * @return student id
     */
    public int inputId() {
        System.out.print("Input student id: ");
        while (true) {
            try {
                int id = Integer.parseInt((scanner.nextLine()));
                return id;
            } catch (NumberFormatException ex) {
                System.out.print("invalid! Input student id again: ");
            }
        }
    }
     
    /**
     * input student name
     *
     * @return student name
     */
    private String inputName() {
        System.out.print("Input student name: ");
        return scanner.nextLine();
    }
 
    /**
     * input student address
     *
     * @return student address
     */
    private String inputAddress() {
        System.out.print("Input student address: ");
        return scanner.nextLine();
    }
 
    /**
     * input student age
     *
     * @return student age
     */
    private byte inputAge() {
        System.out.print("Input student age: ");
        while (true) {
            try {
                byte age = Byte.parseByte((scanner.nextLine()));
                if (age < 0 && age > 100) {
                    throw new NumberFormatException();
                }
                return age;
            } catch (NumberFormatException ex) {
                System.out.print("invalid! Input student id again: ");
            }
        }
    }
 
    /**
     * input student gpa
     *
     * @return gpa
     */
    private float inputGpa() {
        System.out.print("Input student gpa: ");
        while (true) {
            try {
                float gpa = Float.parseFloat((scanner.nextLine()));
                if (gpa < 0.0 && gpa > 10.0) {
                    throw new NumberFormatException();
                }
                return gpa;
            } catch (NumberFormatException ex) {
                System.out.print("invalid! Input student age again: ");
            }
        }
    }
 
    // getter && setter
    public List<Student> getStudentList() {
        return studentList;
    }
 
    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }
}

/////////////
Tao lop main
package vn.viettuts;
 
import java.util.Scanner;
 
/**
 * Main class
 *
 * @author viettuts.vn
 */
public class Main {
    public static Scanner scanner = new Scanner(System.in);
 
    public static void main(String[] args) {
        String choose = null;
        boolean exit = false;
        StudentManager studentManager = new StudentManager();
        int studentId;
 
        // show menu
        showMenu();
        while (true) {
            choose = scanner.nextLine();
            switch (choose) {
            case "1":
                studentManager.add();
                break;
            case "2":
                studentId = studentManager.inputId();
                studentManager.edit(studentId);
                break;
            case "3":
                studentId = studentManager.inputId();
                studentManager.delete(studentId);
                break;
            case "4":
                studentManager.sortStudentByGPA();
                break;
            case "5":
                studentManager.sortStudentByName();
                break;
            case "6":
                studentManager.show();
                break;
            case "0":
                System.out.println("exited!");
                exit = true;
                break;
            default:
                System.out.println("invalid! please choose action in below menu:");
                break;
            }
            if (exit) {
                break;
            }
            // show menu
            showMenu();
        }
    }
 
    /**
     * create menu
     */
    public static void showMenu() {
        System.out.println("-----------menu------------");
        System.out.println("1. Add student.");
        System.out.println("2. Edit student by id.");
        System.out.println("3. Delete student by id.");
        System.out.println("4. Sort student by gpa.");
        System.out.println("5. Sort student by name.");
        System.out.println("6. Show student.");
        System.out.println("0. exit.");
        System.out.println("---------------------------");
        System.out.print("Please choose: ");
    }
}

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import com.microsoft.sqlserver.jdbc.SQLServerException;

import java.sql.*;

public class database {


public static void main(String[] args) {
SQLServerDataSource ds = new SQLServerDataSource();
ds.setUser("Sa"); // user
ds.setPassword("123"); // pass
ds.setServerName("DESKTOP-41NSRI0\\SQLEXPRESS");
ds.setPortNumber(1433); // cong port tcp ip
ds.setDatabaseName("Test3"); // database name
ds.setEncrypt(false);

try (Connection conn = ds.getConnection()) {


System.out.println("Ket noi thanh cong!");
System.out.println(conn.getMetaData());

System.out.println(conn.getClientInfo());
// addddddđ
try {
PreparedStatement pstm1 = conn.prepareStatement("INSERT INTO
IDSinhVien(Ten,Diem) VALUES(?,?)");
pstm1.setString(1,"Loi1");
pstm1.setInt(2,8);
pstm1.executeUpdate();
}catch (SQLException e1){
e1.printStackTrace();
}
try {

PreparedStatement pstm3 = conn.prepareStatement("DELETE from


IDSinhVien WHERE ID=?");
pstm3.setInt(1,8);
pstm3.executeUpdate();
}catch (SQLException e3){
e3.printStackTrace();
}

try {
PreparedStatement pstm = conn.prepareStatement("SELECT * From IDSinhVien");
ResultSet rs = pstm.executeQuery();
while (rs.next()){
System.out.println("id :"+rs.getInt("ID"));
System.out.println("Ten :"+rs.getString("Ten"));
System.out.println("Diem :"+ rs.getInt("Diem"));
}
} catch (SQLException e2) {
e2.printStackTrace();
}
} catch (SQLServerException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}

}
}

You might also like