C3P0数据库Jar包的使用
0.导入数据库相关jar包
commons-dbutils-1.4.jar
c3p0-0.9.1.2.jar
1.配置C3P0-config.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 数据库连接池 -->
<default-config>
<property name="user">root</property>
<property name="password">admins</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///shop</property>
</default-config>
</c3p0-config>
2.然后写一个DataSourceUtils工具类
package com.shop.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 数据库连接工具
*/
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 {
Connection con = tl.get();
if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}
return con;
}
// 开启事务
public static void startTransaction() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.setAutoCommit(false);
}
}
// 事务回滚
public static void rollback() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.rollback();
}
}
// 提交并且关闭资源及从ThreadLocal中释放
public static void commitAndRelease() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.commit(); // 事务提交
con.close();// 关闭资源
tl.remove();// 从线程绑定中移除
}
}
// 关闭资源方法
public static void closeConnection() throws SQLException {
Connection con = getConnection();
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.最后在相关dao中就可以直接使用了
如:查询商品所有分类
//查询商品所有分类
public List<Category> findAllCategory() throws SQLException {
QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
String sql="select * from category";
return runner.query(sql,new BeanListHandler<Category>(Category.class));
}
如:添加商品分类
//添加商品分类
public void saveProductCategory(Category category) throws SQLException{
QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
String sql="insert into category values(?,?)";
runner.update(sql,category.getCid(),category.getCname());
}
这里查询是用query方法,增删改用update方法;
查询需要映射到一个实体类,而增删改往往需要预编译参数