public class UserDao { /** * 注册用户 * */ public int register(User user) throws SQLException { //1.获取QueryRunner QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); //2.编写SQL String sql = "insert into user values(?,?,?,?,?,?)"; Object[] param = {user.getUid(), user.getUsername(), user.getPassword(), user.getTelephone(), user.getBirthday(), user.getSex()}; //3.执行插入操作 int update = qr.update(sql,param); //4.返回受影响的行数 return update; } /** * 用户注册 * */ public User login(String username , String password) throws SQLException { QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); String sql = "select * from user where username = ? and password = ?"; //返回的是一个User对象 使用BeanHandler将结果集的第一条和数据封装到一个Javabean中 User user = qr.query(sql, new BeanHandler<User>(User.class), username, password); return user; } }
public class TestUserDao { //创建UserDao UserDao userDao = new UserDao(); //测试注册功能 @Test public void testRegister() throws SQLException { //1. 创建User对象 User user = new User(); //2. 对User对象进行赋值 user.setUid(UUIDUtils.getUUID()); user.setUsername("大郎"); user.setPassword("654321"); user.setTelephone("15052005200"); user.setSex("男"); user.setBirthday(DateUtils.getDateFormart()); //3.执行注册 int register = userDao.register(user); //4.判断注册是否成功 if(register > 0){ System.out.println("注册成功,欢迎您: " + user.getUsername()); }else{ System.out.println("注册失败! !"); } } //测试登录功能 @Test public void testLogin() throws SQLException { //调用UserDao的 login方法,传入用户名密码 User user = userDao.login("大郎", "654321"); //判断user不为空 登录成功 if(user != null){ System.out.println(user.getUsername() +" 欢迎您!"); }else{ System.out.println("用户名或者密码错误! !"); } } }