[JavaWeb]DBUtils中的QueryRunner

来源:互联网 发布:c语言 strtok s 编辑:程序博客网 时间:2024/06/05 06:39

QueryRunner

QueryRunner中提供对sql语句操作的API
它主要有三个方法
  query() 用于执行select
  update() 用于执行insert/update/delete
  batch() 批处理

public class JdbcUtil {/** * 去src目录下加载c3p0-config.xml配置文件 */private static ComboPooledDataSource dataSource = new ComboPooledDataSource();/** * 获取数据源 */public static ComboPooledDataSource getDataSource() {return dataSource;}}

操作数据

int topicNum=0;        QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());        String sql ="select count(*) from topic where type_id= ? order by time desc";        Object[] params={typeId};        topicNum=(int)(long) runner.query(sql,new ScalarHandler(),params);        return topicNum;


Topic newlyTopic=null;        QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());        String sql ="select * from topic where type_id= ? order by time desc";        Object[] params={typeId};        newlyTopic= runner.query(sql,new BeanHandler<Topic>(Topic.class),params);        return newlyTopic;

List<Topic> topicList=new ArrayList<Topic>();        QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());        String sql ="select * from topic where type_id= ? order by time desc";        Object[] params={typeId};        topicList=runner.query(sql, new BeanListHandler<Topic>(Topic.class),params);        return topicList;

public void add(Emp emp) throws Exception{QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());String sql = "insert into emps(id,username,salary,hiredate) values(?,?,?,?)";Object[] params = {emp.getId(),emp.getUsername(),emp.getSalary(),emp.getHiredate()};runner.update(sql,params);}




阅读全文
0 0
原创粉丝点击