public class JdbcUtil {
private static ComboPooledDataSource dataSource =new ComboPooledDataSource();
public static ComboPooledDataSource getDataSource()
{
return dataSource;
}
}
src目錄下c3p0-config.xml html
從數據庫中取count(*)數據 java
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;
取一條數據 其中表的字段名字和類的名字要對應相同 sql
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; }
更新 spa
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; }