queryRunner和数据池

来源:互联网 发布:德温特专利数据库链接 编辑:程序博客网 时间:2024/04/30 09:00


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

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

 <?xmlversion="1.0"encoding="UTF-8"?>

 

<c3p0-config>

 

 <named-configname="test">

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

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

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

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

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

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

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

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

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

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

 

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

   <propertyname="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
原创粉丝点击