package login;

import common.DBTool;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDB {
    static private DBTool dbtool;
    public UserDB() throws SQLException, ClassNotFoundException {
        if(dbtool == null){
            dbtool = new DBTool();
        }
    }
    public UserInfo GetUserInfo(int id) {
        UserInfo u = new UserInfo();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            String sql = "select * from t_user where N_USER_ID = ?";
            ps = dbtool.getConn().prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            if(rs.next()) {
                u.setId(rs.getInt("N_USER_ID"));
                u.setName(rs.getString("VC_LOGIN_NAME"));
                u.setPass(rs.getString("VC_PASSWORD"));
            }else{
                u = null;
            }
            ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return u;
    }
    public UserInfo GetUserInfoByName(String username) {
        UserInfo u = new UserInfo();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            String sql = "select * from t_user where VC_LOGIN_NAME = ?";
            ps = dbtool.getConn().prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if(rs.next()) {
                u.setId(rs.getInt("N_USER_ID"));
                u.setName(rs.getString("VC_LOGIN_NAME"));
                u.setPass(rs.getString("VC_PASSWORD"));
            }else{
                u = null;
            }
            ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return u;
    }
}
