package com.fjp.servlet.login.dao.impl;
import com.fjp.servlet.login.dao.LoginDao;
import com.fjp.servlet.login.pojo.User;
import com.fjp.servlet.login.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.SQLException;
import java.util.List;
/**
* @author fjp
* @version 1.0
* @description: TODO
* @date 2023/7/19 19:30
*/
public class LoginDaoImpl implements LoginDao {
private static QueryRunner queryRunner = new QueryRunner(DruidUtils.getdataSource());
@Override
public User login(String username, String password) {
String sql = "select * from users where username = ? and password = ?";
try {
return queryRunner.query(sql,new BeanHandler<User>(User.class),username,password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<User> findAll() {
String sql = "select * from users";
try {
return queryRunner.query(sql, new BeanListHandler<User>(User.class));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public User findById(int id) {
String sql = "select * from users where id = ?";
try {
return queryRunner.query(sql,new BeanHandler<User>(User.class),id);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public int updateUser(User user) {
String sql = "update users set username =? , password = ? ,phone = ? where id = ?";
try {
return queryRunner.update(sql, user.getUsername(), user.getPassword(), user.getPhone(), user.getId());
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int deleteUser(int id) {
String sql = "delete from users where id=?";
try {
return queryRunner.update(sql,id);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int addUser(User user) {
String sql = "insert into users values(?,?,?,?)";
try {
return queryRunner.update(sql,user.getId(),user.getUsername(),user.getPassword(),user.getPhone());
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public List<User> limitUser(int page, int pageSize) {
String sql = "select * from users limit ? ,?";
try {
return queryRunner.query(sql,new BeanListHandler<User>(User.class),page,pageSize);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<User> fuzzyFind(String name) {
String sql ="select * from users where username like ?";
try {
return queryRunner.query(sql, new BeanListHandler<User>(User.class),name);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public long countUser() {
String sql = "select count(id) from users";
try {
return queryRunner.query(sql,new ScalarHandler<>());
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}