DBUtils温习2

上篇简单回顾了下DBUtils的简介和其常用的类,这篇博客结合C3P0连接池,做一个简单的增删改查操作

1.创建web项目,导入jar包

2.编写c3p0-config.xml和引入工具类

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

  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3307/test</property>
    <property name="user">root</property>
    <property name="password">123456</property>
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">20</property>
  </default-config>
  
</c3p0-config> 
package DBUtils温习;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {

    private static DataSource dataSource = new ComboPooledDataSource();

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    // 直接可以获取一个连接池
    public static DataSource getDataSource() {
        return dataSource;
    }
    
    public static Connection getConnection() throws SQLException{
        return dataSource.getConnection();
    }

    // 获取连接对象
    public static Connection getCurrentConnection() throws SQLException {

        Connection con = tl.get();
        if (con == null) {
            con = dataSource.getConnection();
            tl.set(con);
        }
        return con;
    }

    // 开启事务
    public static void startTransaction() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.setAutoCommit(false);
        }
    }

    // 事务回滚
    public static void rollback() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.rollback();
        }
    }

    // 提交并且 关闭资源及从ThreadLocall中释放
    public static void commitAndRelease() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.commit(); // 事务提交
            con.close();// 关闭资源
            tl.remove();// 从线程绑定中移除
        }
    }

    // 关闭资源方法
    public static void closeConnection() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.close();
        }
    }

    public static void closeStatement(Statement st) throws SQLException {
        if (st != null) {
            st.close();
        }
    }

    public static void closeResultSet(ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
    }

}

3.编写实体类

package domain;

public class Student {

    private int id;
    private String name;
    private String sex;

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

}

4.编写测试类

package DBUtils温习;
/*
 * 测试类
 */

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import domain.Student;

public class test {

    @Test
    public void add() {
        try {
            // 1.获取核心类
            QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
            // 2.编写sql语句
            String sql = "insert into student values(?,?,?)";
            // 3.设置占位符
            Object params[] = { 12, "王三", "女" };
            // 4.执行添加操作
            int updateRow = qr.update(sql, params);
            if (updateRow > 0) {
                System.out.println("添加成功");
            } else {
                System.out.println("添加失败");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Test
    public void deleteById() {
        try {
            // 1.获取核心类
            QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
            // 2.编写sql语句
            String sql = "delete from student where id=?";
            // 3.设置占位符
            Object params[] = { 11 };
            // 4.执行删除操作
            int updateRow = qr.update(sql, params);
            if (updateRow > 0) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Test
    public void update() {
        try {
            // 1.获取核心类
            QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
            // 2.编写sql语句
            String sql = "update student set name=?,sex=? where id=? ";
            // 3.设置占位符
            Object params[] = { "王四", "男", 12 };
            // 4.执行更新操作
            int updateRow = qr.update(sql, params);
            if (updateRow > 0) {
                System.out.println("更新成功");
            } else {
                System.out.println("更新失败");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Test
    /*
     * 根据ID查询某个学生
     */
    public void findById() {
        try {
            // 1.获取核心类
            QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
            // 2.编写sql语句
            String sql = "select * from student where id=? ";
            // 3.设置占位符
            Object params[] = { 12 };
            // 4.执行查询操作
            Student student = qr.query(sql, new BeanHandler<Student>(Student.class), params);
            System.out.println(student.getName() + " : " + student.getSex());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Test
    /*
     * 查询所有的学生
     */
    public void findAllStudent() {
        try {
            // 1.获取核心类
            QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
            // 2.编写sql语句
            String sql = "select * from student ";
            // 3.执行查询操作
            List<Student> students = qr.query(sql, new BeanListHandler<Student>(Student.class));
            // 4.对结果集进行遍历
            for (Student student : students) {
                System.out.println(student.getName() + " : " + student.getSex());
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Test
    /*
     * 查询学生的总数
     */
    public void totalStudent() {
        try {
            // 1.获取核心类
            QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
            // 2.编写sql语句
            String sql = "select count(*) from student ";
            // 3.执行查询操作
            Long count = (Long) qr.query(sql, new ScalarHandler());
            System.out.println(count.intValue());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

5.补充

qr.query()返回object类型 ,先转成 ScalarHandler的Long类型 然后在转为 int类型
return ((Long) qr.query(sql, new ScalarHandler())).intValue();

原文地址:https://www.cnblogs.com/zengcongcong/p/10371368.html