代码实现:
1.开启事务
conn.setAutoCommit(false);
2.一组业务执行完毕,提交事务
conn.commit();
3.可以在catch语句中显式定义回滚语句,但是默认失败就回滚
conn.rollback();
完整代码:
public class JdbcUtils {
private static final String DRIVER="com.mysql.jdbc.Driver";
private static final String URL="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
private static final String USERNAME="root";
private static final String PASSWORD="root";
public static Connection getConn(){
Connection conn=null;
try {
Class.forName(DRIVER);
conn= DriverManager.getConnection(URL,USERNAME,PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void closeAll(Connection conn, Statement st, ResultSet rs) throws SQLException {
if (rs!=null){
rs.close();
}
if (st!=null){
st.close();
}
if (conn!=null){
conn.close();
}
}
}
public class TestTransaction1 {
public static void main(String[] args) throws SQLException {
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn= JdbcUtils.getConn();
//关闭数据库的自动提交功能,自动开启事务
conn.setAutoCommit(false); //开启事务
String sql1="update account set money=money-100 where name='A'";
st = conn.prepareStatement(sql1);
st.executeUpdate();
String sql2="update account set money=money+100 where name='B'";
st = conn.prepareStatement(sql2);
st.executeUpdate();
//业务完毕,提交事务
conn.commit();
System.out.println("成功!");
} catch (Exception e) {
conn.rollback(); //如果失败,回滚事务
e.printStackTrace();
} finally {
JdbcUtils.closeAll(conn,st,rs);
}
}
}
1.DBCP
需要的jar包
commons pool
dbcpconfig.properties
#连接设置 这里面的名字是DBCP数据源中定义好的
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&uesSSL=true
username=root
password=root
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
maxWait=60000
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=utf8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_COMMITTED
jdbcUtils_DBCP.java
public class jdbcUtils_DBCP {
private static DataSource dataSource=null;
static {
try {
InputStream in = jdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
//创建数据源 工厂模式-->创建
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
//获取连接
public static Connection getConnection() throws SQLException {
//从数据源中获取连接
return dataSource.getConnection();
}
//释放连接资源
public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
if (rs!=null){
rs.close();
}
if (st!=null){
st.close();
}
if (conn!=null){
conn.close();
}
}
}
dbcpTest.java
public class dbcpTest {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//获取数据库连接
conn= jdbcUtils_DBCP.getConnection();
//获得SQL执行对象
st = conn.createStatement();
String sql= "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`) VALUES(4,'p','654231','2123457@qq.com','2020-11-18')";
int i=st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils_DBCP.release(conn,st,rs);
}
}
}
2.C3P0
需要用到的jar包
c3p0
mchange commons java
src目录下创建c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--
c3p0的缺省(默认)配置
如果在代码中"ComboPooledDataSource ds=new ComboPooledDataSource();"这样写就表示使用的是c3p0的缺省(默认)-->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&uesSSL=true&serverTimezone=UTC</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<!--
c3p0的命名配置
如果在代码中"ComboPooledDataSource ds=new ComboPooledDataSource("MySQL");"这样写就表示使用的是mysql的缺省(默认)
-->
<named-config name="MySQL">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&uesSSL=true</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquiredIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
</c3p0-config>
c3p0.java
public class c3poTest {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement st = null;
try {
//获取数据库连接
//原来是自己实现的,现在是别人实现的
conn= jdbcUtils_C3P0.getConnection();
//获得SQL执行对象
st = conn.createStatement();
String sql= "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`) VALUES(5,'p','654231','2123457@qq.com','2020-11-18')";
int i=st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils_C3P0.release(conn,st,null);
}
}
}
结论:
无论使用什么数据源,本质还是一样的,DataSourse接口不会变,方法就不会变