DbUtils工具简化JDBC开发

/**
  * 添加书籍
  * @param book
  */
 public void create(Book book){
  try {
   // 1 操作核心类
   QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
   // 2准备sql语句
   String sql = "insert into book(id,title,price,author) values(?,?,?,?)";
   // 3准备数据
   Object[] params = {book.getId(),book.getTitle(),book.getPrice(),book.getAuthor()};
   // 4执行
   runner.update(sql, params);
  } catch (SQLException e) {
   throw new RuntimeException(e.getMessage(),e);
  }
 }
 
 /**
  * 查询所有
  * @return
  */
 public List<Book> findAll(){
  try {
   QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
   String sql = "select * from book";
   return runner.query(sql, new BeanListHandler<Book>(Book.class));
  } catch (SQLException e) {
   throw new RuntimeException(e.getMessage(),e);
  }
 }

你可能感兴趣的:(jdbc,DbUtils)