DAO

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.8 kB
2
Indexable
Never
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package DAOs;

import DatabaseConnection.DatabaseConnection;
import EncodeMD5.MD5;
import Models.Account;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author khoic
 */
public class AccountDAO {
    
    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;
    
    public AccountDAO() throws Exception {
        conn = DatabaseConnection.getConnection();
    }
    
    public boolean Login(Account acc) throws SQLException {
        String sql = "SELECT * FROM Account WHERE Username=? AND Password=?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, acc.getUsername());
            ps.setString(2, MD5.encode(acc.getPassword()));
            rs = ps.executeQuery();
        } catch (Exception ex) {
            Logger.getLogger(AccountDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rs.next();
    }
    
    public boolean IsAdmin(String username) {
        String sql = "SELECT IsAdmin FROM Account WHERE Username = ?";

        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                int isAdmin = rs.getInt("IsAdmin");
                return (isAdmin == 1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }
    
    
    public String GetFullName(String username) {
        String fullname = null;

        try {
            ps = conn.prepareStatement("select Fullname from Account where Username=?");
            ps.setString(1, username);
            rs = ps.executeQuery();
            if (rs.next()) {
                fullname = rs.getString("Fullname");
            }
        } catch (SQLException ex) {

        }
        return fullname;

    }
    
    public int GetIDFromFullname(String Fullname) {
        int ID = 0;
        String sql = "select Account_ID from Account\n"
                + "where Fullname = ?;";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, Fullname);
            rs = ps.executeQuery();
            if (rs.next()) {
                ID = rs.getInt("Account_ID");
            }
        } catch (SQLException e) {
        }
        return ID;
    }
}