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工具类
packagecom.shop.utils;
importcom.mchange.v2.c3p0.ComboPooledDataSource;
importjavax.sql.DataSource;
importjava.sql.Connection;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
/*** 数据库连接工具
*/
public classDataSourceUtils {
private static DataSource dataSource = newComboPooledDataSource();
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
//直接可以获取一个连接池
public staticDataSource getDataSource() {
returndataSource;
}
//获取连接对象
public static Connection getConnection() throwsSQLException {
Connection con =tl.get();
if (con == null) {
con =dataSource.getConnection();
tl.set(con);
}
returncon;
}
//开启事务
public static void startTransaction() throwsSQLException {
Connection con =getConnection();
if (con != null) {
con.setAutoCommit(false);
}
}
//事务回滚
public static void rollback() throwsSQLException {
Connection con =getConnection();
if (con != null) {
con.rollback();
}
}
//提交并且关闭资源及从ThreadLocal中释放
public static void commitAndRelease() throwsSQLException {
Connection con =getConnection();
if (con != null) {
con.commit(); //事务提交
con.close();//关闭资源
tl.remove();//从线程绑定中移除
}
}
//关闭资源方法
public static void closeConnection() throwsSQLException {
Connection con =getConnection();
if (con != null) {
con.close();
}
}
public static void closeStatement(Statement st) throwsSQLException {
if (st != null) {
st.close();
}
}
public static void closeResultSet(ResultSet rs) throwsSQLException {
if (rs != null) {
rs.close();
}
}
}
3.最后在相关dao中就可以直接使用了
如:查询商品所有分类
//查询商品所有分类
public List<Category> findAllCategory() throwsSQLException {
QueryRunner runner=newQueryRunner(DataSourceUtils.getDataSource());
String sql="select * from category";
return runner.query(sql,new BeanListHandler<Category>(Category.class));
}
如:添加商品分类
//添加商品分类
public void saveProductCategory(Category category) throwsSQLException{
QueryRunner runner=newQueryRunner(DataSourceUtils.getDataSource());
String sql="insert into category values(?,?)";
runner.update(sql,category.getCid(),category.getCname());
}
这里查询是用query方法,增删改用update方法;
查询需要映射到一个实体类,而增删改往往需要预编译参数