您的位置:首页 > 产品设计 > UI/UE

queryRunner和数据池

2016-08-11 18:26 169 查看
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
class
Jdbcs {
   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
class
Demo {
  
   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("更新数据出错!");
      }
   }
小伙伴们,赶快将这个方法加载到自己的项目中吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息