DbUtil工具类
public class DbUtil { private static String url = "jdbc:mariadb://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"; private static String username = "test"; private static String password = "test"; public static Connection getConnection() { Connection conn = null; try { Class.forName("org.mariadb.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { e.printStackTrace(); } return conn; } }
2.Dao类
public class UserDao { //查询所有 public List<User> findAll(){ //创建连接 Connection conn = DbUtil.getConnection(); //创建SQL执行工具 QueryRunner queryRunner = new QueryRunner(); List<User> list = null; try { //执行SQL查询,并获取结果 //BeanListHandler 映射多个对象 list = queryRunner.query(conn, "select * from user", new BeanListHandler<>(User.class)); } catch (SQLException e) { e.printStackTrace(); } //关闭数据库连接 DbUtils.closeQuietly(conn); return list; } //添加 public void save(User user) { Connection conn = DbUtil.getConnection(); //创建SQL执行工具 QueryRunner queryRunner = new QueryRunner(); int rows = 0; try { //执行SQL插入 //返回受影响有多少行 rows = queryRunner.update(conn, "INSERT INTO user(name, age,imgurl) VALUES(?,?,?)", new Object[] {user.getName(),user.getAge(),user.getImgurl()}); //new Object[] {user.getName(),user.getAge(),user.getImgurl()} 设置参数 } catch (SQLException e) { e.printStackTrace(); } //关闭数据库连接 DbUtils.closeQuietly(conn); } //查找单个 public User findOne(int id) { //创建连接 Connection conn = DbUtil.getConnection(); //创建SQL执行工具 QueryRunner queryRunner = new QueryRunner(); User user = new User(); try { //执行SQL查询,并获取结果 //BeanHandler 映射成一个对象 user = queryRunner.query(conn, "select * from user where id=?", new BeanHandler<>(User.class), new Object[] {id}); } catch (SQLException e) { e.printStackTrace(); } //关闭数据库连接 DbUtils.closeQuietly(conn); return user; } //修改 public void update(User user) { Connection conn = DbUtil.getConnection(); //创建SQL执行工具 QueryRunner queryRunner = new QueryRunner(); int rows = 0; try { //执行SQL插入 rows = queryRunner.update(conn, "update user set name=?,age=?,imgurl=? where id=?", new Object[] {user.getName(),user.getAge(),user.getImgurl(),user.getId()}); //new Object[] {user.getName(),user.getAge(),user.getImgurl()} 设置参数 } catch (SQLException e) { e.printStackTrace(); } //关闭数据库连接 DbUtils.closeQuietly(conn); } //删除 public void delete(int id) { Connection conn = DbUtil.getConnection(); //创建SQL执行工具 QueryRunner queryRunner = new QueryRunner(); int rows = 0; try { //执行SQL插入 rows = queryRunner.update(conn,"delete from user where id=?", new Object[] {id}); } catch (SQLException e) { e.printStackTrace(); } //关闭数据库连接 DbUtils.closeQuietly(conn); } }