概述


代码实现

package cn.tedu.transaction;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TransDemo1 {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
ComboPooledDataSource source=new ComboPooledDataSource();
try {
conn = source.getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement("update user set money=money-100 where name=?");
ps.setString(1,"a");
ps.executeUpdate();
ps = conn.prepareStatement("update user set money=money+100 where name=?");
ps.setString(1,"b");
ps.executeUpdate();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
if(conn!=null)
try {
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}finally {
if(ps!=null)
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
ps=null;
}
if(conn!=null)
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
conn=null;
}
}
}
}
带保存点的事务

package cn.tedu.transaction;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.*;
public class TransDemo2 {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
Savepoint sp=null;
ComboPooledDataSource source=new ComboPooledDataSource();
try {
conn = source.getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement("update user set money=money-100 where name=?");
ps.setString(1,"a");
ps.executeUpdate();
ps = conn.prepareStatement("update user set money=money+100 where name=?");
ps.setString(1,"b");
ps.executeUpdate();
sp = conn.setSavepoint();
int i=1/0;
ps = conn.prepareStatement("update user set money=money-100 where name=?");
ps.setString(1,"a");
ps.executeUpdate();
ps = conn.prepareStatement("update user set money=money+100 where name=?");
ps.setString(1,"b");
ps.executeUpdate();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
if(conn!=null)
try {
if(sp!=null){
conn.rollback(sp);
conn.commit();
}else{
conn.rollback();
}
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}finally {
if(ps!=null)
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
ps=null;
}
if(conn!=null)
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
conn=null;
}
}
}
}