使用dbutils获取tomcat数据库连接池

 

使用连接池操作数据

添加数据库连接池(在context.xml)
<Resource name="jdbc/mysql"
                    auth="Container"
                                type="javax.sql.DataSource"
                                maxActive="100"
                                maxIdle="30"
                                maxWait="1000"
                                username="root"
                                password="123"
                                driverClassName="com.mysql.jdbc.Driver"
                                url="jdbc:mysql://127.0.0.1/wb"/>

使用连接池
                DataSource ds=null;
               
                try {
                        Context context = new InitialContext();
                        ds =(DataSource) context.lookup("java:/comp/env/jdbc/mysql");
                       
                } catch (Exception e) {
                        System.out.println("获取数据源时出错");
                }

数据添加
                try {
                        Connection conn=ds.getConnection();
                        String sql="insert into blog(title,content,category_id,created_time) values (?,?,?,now())";
                    PreparedStatement pstmt=conn.prepareStatement(sql);
                    pstmt.setString(1,title);
                    pstmt.setString(2, content);
                    pstmt.setInt(3, Integer.parseInt(categoryID));
                    int result=pstmt.executeUpdate();
                    String message="";
                    if(result==1){
                            message="添加博文成功";
                    }else{
                            message="添加博文失败";
                    }
                    request.setAttribute("message", message);
                    request.getRequestDispatcher("/addBlogResult.jsp").forward(request, response);
                } catch (SQLException e) {
                        e.printStackTrace();
                }

使用DbUtils添加数据
                int result=0;
                try {
                        //添加博文的SQL语句,now()生成当前系统时间
                       
                        String sql = "insert into blog(title,content,category_id,created_time) values (?,?,?,now())";
                    //为SQL语句中的?设定参数
                        String params[]={title,content,categoryID};
                        //DButils中核心类,生成对象时传递数据源对象
                        QueryRunner qr=new QueryRunner(ds);
                        //调用它的update,完成SQL的运行。其他使用update方法的SQL语句:insert into/update/delete
                        result=qr.update(sql, params);
                } catch (SQLException e) {
                        e.printStackTrace();
                }
                String message = "";
                        if (result == 1) {
                                message = "添加博文成功";
                        } else {
                                message = "添加博文失败";
                        }
                        request.setAttribute("message", message);
                        request.getRequestDispatcher("/addBlogResult.jsp").forward(request,
                                        response);

 

使用dbutils获取tomcat数据库连接池(为测试)
1、首先要将mysql的驱动包放在tomcat/lib目录下

2、在myeclipse工程目录下的webroot/META-INF下新建一个context.xml文件,内容如下:

<Context>

<!--这里是mysql的连接池设置-->
   <Resource
    name="jdbc/mysqlds"
    auth="Container"
    type="javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://127.0.0.1/blog"
    username="root"
    password="root"
    maxActive="100"
    maxIdle="30"
    maxWait="10000" />  

<!--这里是oracle的连接池设置-->

<Resource name="jdbc/oracleds"
   auth="Container"
   type="javax.sql.DataSource"
   maxActive="100"
   maxIdle="30"
   maxWait="10000"
   username="scott"
   password="tiger"
    driverClassName="oracle.jdbc.driver.OracleDriver"
   url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
   </Context>

3、在需要用连接池的地方使用如下:

mysql下使用连接池:  

Context ctx = new InitialContext();
   DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysqlds");
   Connection conn = ds.getConnection();

oracle下使用连接池:  

Context ctx = new InitialContext();
   DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracleds");
   Connection conn = ds.getConnection();

 

dbutils是一个开源的对JDBC进行封装的组件,简化了对JDBC的操作。

首先当然是到官方网站上把源码下载下来,http://commons.apache.org/dbutils/

然后解压后,把commons-dbutils.jar放在工程名称/WebRoot/WEB-INF/lib目录下,就可直接使用了。

以下是使用dbutils获取QueryRnner的代码DbHelper.java:

package com.xie.dbutils;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

public class DbHelper {
public static QueryRunner getQueryRunner() {
DataSource ds = null;
try {
   Context context = new InitialContext();
   ds = (DataSource) context.lookup("java:/comp/env/jdbc/oracleds");
   //System.out.println("oracle连接池成功");
} catch (Exception e) {
   System.out.println("oracle连接池失败");
}
QueryRunner qr = new QueryRunner(ds);
return qr;
}
}
查询就直接使用QueryRunner里的query();方法就可以了,其它的增删改就直接用QueryRunner里的update();方法就行了。

如下是查询的示例:

String sql = "select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp";
   QueryRunner qr = DbHelper.getQueryRunner();
   List list = (List) qr.query(sql, new BeanListHandler(Emp.class));

如下是删除的示例:

String id = request.getParameter("id");
String sql = "delete from comment where id=" + id;
QueryRunner qr = DbHelper.getQueryRunner();
   qr.update(sql);

如下是修改的示例:

String id = request.getParameter("id");
String username = request.getParameter("name");
String content = request.getParameter("content");
String sql = "update comment set username=?,content=? where id=?";
String params[] = { username, content, id };
QueryRunner qr = DbHelper.getQueryRunner();
   qr.update(sql, params);

如下是增加的示例

String name = request.getParameter("name");
String content = request.getParameter("content");
String blog_id = request.getParameter("blog_id");

if (name == null || name.equals("")) {
   name = "匿名";
}

String sql = "insert into comment (username,content,blog_id,createdtime) values (?,?,?,now())";
String params[] = { name, content, blog_id };

QueryRunner qr = DbHelper.getQueryRunner();
   qr.update(sql, params); 

 

DBUtils 是一个开源的 JDBC 工具库,它提供了一组简单易用的 API,帮助我们更方便地使用 JDBC 操作数据库。其中,DBCP(DataBase Connection Pool)是 DBUtils 提供的一个数据库连接池,可以有效地管理数据库连接,提高应用程序的性能和稳定性。 下面是利用 DBUtils 创建数据库连接池的步骤: 1. 导入相关依赖包(DBUtils 和数据库驱动)。 2. 在配置文件中设置数据库连接信息,包括数据库 URL、用户名、密码等。 3. 使用 BasicDataSource 对象创建一个连接池,并设置相关参数,如最大连接数、最大空闲时间等。 4. 通过连接获取数据库连接,执行 SQL 操作。 下面是一个示例代码: ```java import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; public class DBUtilsDemo { public static void main(String[] args) { // 配置数据库连接信息 String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "123456"; // 创建连接池 BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setInitialSize(5); dataSource.setMaxTotal(10); dataSource.setMaxIdle(8); dataSource.setMaxWaitMillis(10000); // 获取连接并执行 SQL 操作 try(Connection conn = dataSource.getConnection()) { QueryRunner runner = new QueryRunner(); String sql = "SELECT * FROM student"; BeanListHandler<Student> handler = new BeanListHandler<>(Student.class); List<Student> students = runner.query(conn, sql, handler); // 处理查询结果 } catch (SQLException e) { e.printStackTrace(); } } } ``` 在上面的示例代码中,我们首先通过 BasicDataSource 对象设置了数据库连接信息,并创建了一个连接池。然后,通过 getConnection() 方法从连接池中获取一个数据库连接,并使用 QueryRunner 对象执行了一条 SQL 查询语句。最后,我们可以对查询结果进行处理。注意,在使用完数据库连接后,需要及时释放连接,否则会导致连接泄漏,从而影响应用程序的性能和稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值