javaSE|javaEE JDBC, dbutils插件, 事务


MySql驱动(jar包)下载:https://pan.baidu.com/s/19BYnGbO3l5MOOic5K4Ooaw密码:mwoh
第三方插件(commons-dbutils)下载:https://pan.baidu.com/s/17cyAXHZLgiayx5Y_VHvawQ密码:6om2
c3p0连接池下载(jar包,和xml配置文件): https://pan.baidu.com/s/18DodkCHFi07MQdTGACQU7Q 密码:m6fq

Demo.java:

package com.xxx.dbutils; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import com.xxx.utils.DataSourceUtils; // 自定义的获取DataSource和Connection的工具类public class Demo { public static void main(String[] args) {Connection conn = null; try { // 如果需要事务的话,就不能用DataSource(连接池)来实例化QueryRunner。 QueryRunner runner = new QueryRunner(); // 事务,不用DataSource而需要获得Connection conn = DataSourceUtils.getConnection(); //开启事务 conn.setAutoCommit(false); // runner执行sql语句时,需要传入开启事务的conn runner.update(conn, "update account set money=15000 where name='tom'"); //runner.update("update account set money=15000 where name='tom'"); //提交事务 conn.commit(); } catch (SQLException e) { try { conn.rollback(); // 事务回滚 } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } } }

DataSourceUtils.java(自定义的获取DataSource和Connection的工具类):
package com.xxx.utils; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DataSourceUtils { // c3p0连接池 private static ComboPooledDataSource dataSource = new ComboPooledDataSource(); //获得Connection ----- 从连接池中获取 public static Connection getConnection() throws SQLException{ return dataSource.getConnection(); } // 获取一个连接池 public static DataSource getDataSource() { return dataSource; }}

c3p0-config.xml(c3p0连接池配置文件):
root123com.mysql.jdbc.Driverjdbc:mysql:///数据库名


【javaSE|javaEE JDBC, dbutils插件, 事务】

    推荐阅读