1.效果java
2.準備mysql
2.1導入須要的jarsql
2.2 導入c3p0工具類數據庫
c3p0工具類代碼apache
package cn.ma.utils;工具
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;測試
import javax.sql.DataSource;.net
import com.mchange.v2.c3p0.ComboPooledDataSource;xml
public class C3P0utils {
/**
* 1.建立一個鏈接池對象
*/
static DataSource ds = new ComboPooledDataSource();
public static DataSource getDataSource(){
return ds;
}
/**
* 2.從池中得到一個鏈接
* @Title: getConnection
* @Description:
* @return
* @throws SQLException
* @return Connection
* @throws
*/
public static Connection getConnection() throws SQLException{
return ds.getConnection();
}
/**
* 3.釋放資源
* @Title: closeAll
* @Description:
* @param rs
* @param stmt
* @param conn
* @return void
* @throws
*/
public static void closeAll(ResultSet rs,Statement stmt,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
stmt = null;
}
if(conn!=null){
try {
conn.close();//放心的關。是否關閉取決鏈接是怎麼來的
} catch (SQLException e) {
throw new RuntimeException(e);
}
conn = null;
}
}對象
}
2.3 c3p0 鏈接數據庫的xml文件
代碼
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day19</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">10</property>
</default-config>
</c3p0-config>
2.4 數據庫表結構
3.測試 類
代碼:
package cn.ma.transitionManager;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import cn.ma.utils.C3P0utils;
public class C3P0transitionManager { @Test public void TestC3P0transitionManager(){ Connection conn=null; QueryRunner qr = new QueryRunner();//1.使用無參對象,才能控制事務 try { conn = C3P0utils.getConnection();//2.手動獲得鏈接 conn.setAutoCommit(false);//3.手動提交事務 String sql="update t_transitionManager set money=money-100 where accountnumber='999'"; String sql2="update t_transitionManager set money=money+100 where accountnumber='666'"; qr.update(conn,sql);//4.這裏必須將鏈接對象傳遞 int i=1/0; //5.製造異常 qr.update(conn,sql2); conn.commit();//6.沒有異常提交事務 } catch (SQLException e) { e.printStackTrace(); try { conn.rollback();//7.有異常回滾 } catch (SQLException e1) { e1.printStackTrace(); } }finally { if(conn !=null){ try { conn.close();//8.關閉鏈接 } catch (SQLException e) { e.printStackTrace(); } } } } }