queryRunner和数据池


1、  新建工程,导入mysql、c3p0、dbUtil的jar包(c3p0有2个)和c3p0的配置文件

2、  设置好配置文件连接数据库的相关信息

 <?xml version="1.0"encoding="UTF-8"?>

 

<c3p0-config>

 

 <named-config name="test">

 <!-- 数据库用户名和密码 -->

  <property name="user">root</property>

   <property name="password">root</property>

     <!-- 数据库路径和加载的驱动 -->

   <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>

   <property name="driverClass">com.mysql.jdbc.Driver</property>

     <!-- 数据池的相关设置 -->    <property name="acquireIncrement">5</property>

    <property name="initialPoolSize">10</property>

   <property name="minPoolSize">5</property>

   <property name="maxPoolSize">10</property>

 

   <property name="maxStatements">200</property>

   <property name="maxStatementsPerConnection">500</property>

 

 </named-config>

</c3p0-config>

3、  装载dbUtil,实例一个ComboPooledDataSource,并创建一个获取连接的方法getConnection和一个获取连接资源的方法

 

 public classJdbcs {

   private static ComboPooledDataSource ds = null;

   static {

      ds = new ComboPooledDataSource("test");

   }

 

   public static ConnectiongetConnection() throwsSQLException {

      return ds.getConnection();

   }

   public static DataSourcegetDataSourse(){

      return ds;

   }

}

4、      创建一个对数据库操纵的类Demo

 public classDemo {

  

   public void add(){

      QueryRunnerqr=newQueryRunner(Jdbcs.getDataSourse());

      Stringsql="insert into uservalues(?,?,?,?)";

      Objectparams[]={"11","123","name01","school01"};

      try {

        qr.update(sql,params);

      }catch(SQLException e) {

        System.out.println("添加数据出错!");

      }

   }

  

   public void delete(){

      QueryRunnerqr=newQueryRunner(Jdbcs.getDataSourse());

      Stringsql="delete from user where uid=?";

      try {

        qr.update(sql,"11");

      }catch(SQLException e) {

        System.out.println("删除数据出错!");

      }

   }

  

   public void update(){

      QueryRunnerqr=newQueryRunner(Jdbcs.getDataSourse());

      Stringsql="update user set sname=? whereuid=?";

      Objectparams[]={"zhangsan","11"};

      try {

        qr.update(sql,"11");

      }catch(SQLException e) {

        System.out.println("更新数据出错!");

      }

   }

  

   public void select(){

      QueryRunnerqr=newQueryRunner(Jdbcs.getDataSourse());

      Stringsql="select sname from user whereuid=?";

      try {

        Useru=qr.query(sql, "11", new BeanHandler(User.class));

        System.out.println(u.getSname());

      }catch(SQLException e) {

        System.out.println("更新数据出错!");

      }

   }

小伙伴们,赶快将这个方法加载到自己的项目中吧

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值