By GokiSoft.com| 19:43 24/08/2021|
Java Advanced

[Share Code] Tìm hiểu kết nối CSDL MySQL vs Java qua dự án quản lý thông tin người dùng - Lập trình Java nâng cao - C2010L



B1. Tai thu vien mysql jdbc driver maven
B2. Add vao project
B3. Phat trien chuc nang
- Hoc ket noi CSDL
	- Lay danh nguoi dung -> select
	- Them -> insert
	- Sua -> update
	- Xoa -> delete

- Phat trien du an theo menu chuong trinh sau
1. Nhap thong tin user
2. Hien thi thong tin user vua nhap
3. Them vao database
4. Cap nhat user theo id -> update db
5. Xoa user khoi db
6. Hien thi toan bo user tu db
7. Thoat




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

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Utility {
    public static int scanInt(Scanner scan) {
        int value;
        while(true) {
            try {
                value = Integer.parseInt(scan.nextLine());
                return value;
            } catch(NumberFormatException e) {
                System.out.println("Nhap lai: ");
            }
        }
    }
}


#Users.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.lesson06;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Users {
    int id;
    String fullname, email, birthday, password, address;

    public Users() {
    }

    public Users(int id, String fullname, String email, String birthday, String password, String address) {
        this.id = id;
        this.fullname = fullname;
        this.email = email;
        this.birthday = birthday;
        this.password = password;
        this.address = address;
    }

    public Users(String fullname, String email, String birthday, String password, String address) {
        this.fullname = fullname;
        this.email = email;
        this.birthday = birthday;
        this.password = password;
        this.address = address;
    }

    public int getId() {
        return id;
    }

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

    public String getFullname() {
        return fullname;
    }

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

    public String getEmail() {
        return email;
    }

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

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
    public void input() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Nhap ten: ");
        fullname = scan.nextLine();
        
        System.out.println("Nhap email: ");
        email = scan.nextLine();
        
        System.out.println("Nhap ngay sinh(yyyy-mm-dd): ");
        birthday = scan.nextLine();
        
        System.out.println("Nhap mat khau: ");
        password = scan.nextLine();
        
        System.out.println("Nhap dia chi: ");
        address = scan.nextLine();
    }

    @Override
    public String toString() {
        return "Users{" + "id=" + id + ", fullname=" + fullname + ", email=" + email + ", birthday=" + birthday + ", password=" + password + ", address=" + address + '}';
    }
    
    public void display() {
        System.out.println(this);
    }
}


#UserModify.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.lesson06;

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

/**
 *
 * @author Diep.Tran
 */
public class UserModify {

    public static void insert(Users users) {
        Connection conn = null;
        PreparedStatement statement = null;

        try {
            //Mo ket noi toi database
            conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);

            //Thuc hien truy van toi database -> insert
            String sql = "insert into users(fullname, email, birthday, password, address) values (?, ?, ?, ?, ?)";
            statement = conn.prepareStatement(sql);
            statement.setString(1, users.getFullname());
            statement.setString(2, users.getEmail());
            statement.setString(3, users.getBirthday());
            statement.setString(4, users.getPassword());
            statement.setString(5, users.getAddress());

            statement.execute();

            System.out.println("Insert thanh cong");
        } catch (SQLException ex) {
            System.out.println("Insert loi");
            Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            //Dong ket noi toi database
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public static void update(Users users) {
        Connection conn = null;
        PreparedStatement statement = null;

        try {
            //Mo ket noi toi database
            conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);

            //Thuc hien truy van toi database -> insert
            String sql = "update users set fullname = ?, email = ?, birthday = ?, password = ?, address = ? where id = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, users.getFullname());
            statement.setString(2, users.getEmail());
            statement.setString(3, users.getBirthday());
            statement.setString(4, users.getPassword());
            statement.setString(5, users.getAddress());
            statement.setInt(6, users.getId());

            statement.execute();

            System.out.println("Update thanh cong");
        } catch (SQLException ex) {
            System.out.println("Update loi");
            Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            //Dong ket noi toi database
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public static void delete(int id) {
        Connection conn = null;
        PreparedStatement statement = null;

        try {
            //Mo ket noi toi database
            conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);

            //Thuc hien truy van toi database -> insert
            String sql = "delete from users where id = ?";
            statement = conn.prepareStatement(sql);
            statement.setInt(1, id);

            statement.execute();

            System.out.println("Xoa thanh cong");
        } catch (SQLException ex) {
            System.out.println("Xoa loi");
            Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            //Dong ket noi toi database
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public static List<Users> getUserList(String email) {
        List<Users> dataList = new ArrayList<>();
        
        Connection conn = null;
        PreparedStatement statement = null;

        try {
            //Mo ket noi toi database
            conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);

            //Thuc hien truy van toi database -> insert
            String sql = "select * from users";
            if(email != null) {
                sql += " where email like ?";
            }
            
            statement = conn.prepareStatement(sql);
            
            if(email != null) {
                statement.setString(1, email);
            }

            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next()) {
                Users u = new Users(
                        resultSet.getInt("id"),
                        resultSet.getString("fullname"),
                        resultSet.getString("email"),
                        resultSet.getString("birthday"),
                        resultSet.getString("password"),
                        resultSet.getString("address")
                );
                dataList.add(u);
            }
        } catch (SQLException ex) {
            Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            //Dong ket noi toi database
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(UserModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return dataList;
    }
}


#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 java2.lesson06;

import java.util.List;
import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Main {

    public static void main(String[] args) {
        Users users = new Users();

        Scanner scan = new Scanner(System.in);
        int choose;

        do {
            showMenu();
            choose = Utility.scanInt(scan);

            switch (choose) {
                case 1:
                    System.out.println("Nhap thong tin user: ");
                    users.input();
                    break;
                case 2:
                    users.display();
                    break;
                case 3:
                    //ORM -> select, insert, update, delete, find.
                    //CRUD -> UserModify (select, insert, update, delete, find)
                    UserModify.insert(users);
                    break;
                case 4:
                    System.out.println("Nhap ID can sua: ");
                    int id = Utility.scanInt(scan);
                    users.setId(id);
                    System.out.println("Nhap thong tin can update: ");
                    users.input();
                    UserModify.update(users);
                    break;
                case 5:
                    System.out.println("Nhap ID can xoa: ");
                    int delId = Utility.scanInt(scan);
                    UserModify.delete(delId);
                    break;
                case 6:
                    System.out.println("Danh sach users trong database");
                    List<Users> userList = UserModify.getUserList(null);

                    for (Users u : userList) {
                        u.display();
                    }
                    break;
                case 7:
                    System.out.println("Nhap email tim kiem (like): ");
                    String email = scan.nextLine();

                    List<Users> searchUserList = UserModify.getUserList("%" + email + "%");

                    if (searchUserList.isEmpty()) {
                        System.out.println("Khong tim thay user nao co email tren");
                    } else {
                        for (Users u : searchUserList) {
                            u.display();
                        }
                    }

                    break;
            }
        } while (choose != 8);
    }

    static void showMenu() {
        System.out.println("1. Nhap thong tin user");
        System.out.println("2. Hien thi thong tin vua nhap");
        System.out.println("3. Insert user into db");
        System.out.println("4. Update user theo id");
        System.out.println("5. Delete user theo id");
        System.out.println("6. Select all user tu db");
        System.out.println("7. Tim kiem theo email");
        System.out.println("8. Thoat");
        System.out.println("Chon: ");
    }
}


#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 java2.lesson06;

/**
 *
 * @author Diep.Tran
 */
public interface Config {
    String DB_NAME = "C2010L";
    //Dung MySQL.
    String DB_URL = "jdbc:mysql://localhost:3306/" + DB_NAME;//public static final String -> String
    String USERNAME = "root";//public static final String -> String
    String PASSWORD = "";//public static final String -> String
}


Tags:

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

5

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