1. package com.xf.dao;
    2. import com.xf.beans.UserInfo;
    3. import com.xf.utils.DBManager;
    4. import org.apache.commons.dbutils.QueryRunner;
    5. import org.apache.commons.dbutils.handlers.BeanHandler;
    6. import java.sql.Connection;
    7. import java.sql.SQLException;
    8. //对用户进行CRUD操作,增删改查
    9. public class UserDao {
    10. QueryRunner qr = new QueryRunner();//进行crud操作
    11. //登陆实现:通过用户输入对用户名与密码,对数据库数据进行查询,如果次用户名与密码查询到用户代表登陆成功,如果没有查询到用户,代表登陆失败
    12. //登陆功能,返回用户对象
    13. public UserInfo login(String username,String password){
    14. //通过工具类去获取数据库连接
    15. Connection conn = DBManager.getConn();
    16. //qr执行查询连接 sql语句
    17. try {
    18. return qr.query(conn,"select * from userinfo where id=? and loginpwd=?",new BeanHandler<>(UserInfo.class),username,password);
    19. } catch (SQLException e) {
    20. e.printStackTrace();
    21. }finally {
    22. try {
    23. conn.close();
    24. } catch (SQLException e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. return null;
    29. }
    30. //注册功能,昵称,密码
    31. public int register(String nickName,String password){
    32. Connection conn = DBManager.getConn();
    33. try {
    34. int count = qr.execute(conn,"insert into userinfo (nickname,loginpwd,age) values (?,?,?)",nickName,password,18);
    35. return count;
    36. } catch (SQLException e) {
    37. e.printStackTrace();
    38. }
    39. return 0;
    40. }
    41. //获取最后注册到到用户信息
    42. public UserInfo getRegisterUser(){
    43. //通过工具类去获取数据库连接
    44. Connection conn = DBManager.getConn();
    45. //qr执行查询连接 sql语句
    46. try {
    47. return qr.query(conn,"select * from userinfo order by id desc LIMIT 1 ",new BeanHandler<>(UserInfo.class));
    48. } catch (SQLException e) {
    49. e.printStackTrace();
    50. }finally {
    51. try {
    52. conn.close();
    53. } catch (SQLException e) {
    54. e.printStackTrace();
    55. }
    56. }
    57. return null;
    58. }
    59. public static void main(String[] args) {
    60. UserDao userDao =new UserDao();
    61. //System.out.println(userDao.login("10001","520520"));
    62. userDao.register("小甜甜","111111");
    63. }
    64. }