QueryRunner的使用(转载)

QueryRunner的使用(转载点击看原文)

public class JdbcUtil {
    private static ComboPooledDataSource dataSource =new ComboPooledDataSource();
    public static ComboPooledDataSource getDataSource()
    {
        return dataSource;
    }

}
src目录下c3p0-config.xml

 

从数据库中取count(*)数据

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<>返回    其中表的字段名字和类的名字要对应相同

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;



插入
QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());
        String sql ="insert into topic(name,author,content,time,type_id) values(?,?,?,?,?)";
        Object[] params={topic.getName(),topic.getAuthor(),topic.getContent(),topic.getTime(),topic.getTypeId()};
        try {
            //事务开始
            runner.update(sql,params);
            //事务提交
        } catch (SQLException e) {
            e.printStackTrace();
            //事务回滚
            throw e;
        }

更新

QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());
        String sql ="update topic set name=? , content=? , time=? where id= ?";
        Object[] params={topic.getName(),topic.getContent(),topic.getTime(),topic.getId()};
        try {
            //事务开始
            runner.update(sql,params);
            //事务提交
        } catch (SQLException e) {
            e.printStackTrace();
            //事务回滚
            throw e;
        }


 

 

转载于:https://my.oschina.net/u/1273559/blog/309629

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值