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;
}