日期:2014-05-16 浏览次数:20410 次
package com.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionManager { private static Connection connection; public static Connection getConnection() throws ClassNotFoundException, SQLException{ Class.forName("com.mysql.jdbc.Driver");//加载驱动类 connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); return connection; } }?
package com.test; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Statement; import com.db.ConnectionManager; /** * JDBC设置事务隔离级别 * @author 守望幸福 * */ public class UnAutoCommit { static Connection con; public static void main(String[] args) throws SQLException { try { con=ConnectionManager.getConnection(); con.setAutoCommit(false);//connection默认自动提交事务,false为不自动提交 DatabaseMetaData dm=con.getMetaData(); System.out.println("是否支持事务隔离"+dm.supportsTransactions()); System.out.println("支持事务隔离0"+dm.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE)); System.out.println("支持事务隔离1"+dm.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED)); System.out.println("支持事务隔离2"+dm.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED)); System.out.println("支持事务隔离4"+dm.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ)); System.out.println("支持事务隔离8"+dm.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE)); con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);//设置事务隔离级别 Statement stmt=con.createStatement(); int row=stmt.executeUpdate("insert into student(name,score,subject)values('李四',20,'数学')"); System.out.println("事务提交前row:"+row); con.commit(); System.out.println("事务提交后row:"+row); } catch (Exception e) { con.rollback(); } } }?
package com.test; import java.sql.Connection; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; import com.db.ConnectionManager; /** * SavePoint JDBC3之后引入的新特性 * SavePoint 接口允许用户将事务分割为多个阶段, 用户可以指定回滚事务到特定保存点,并不会回滚到事务的起点 * @author 守望幸福 * */ public class SavePoint { static Connection con; public static void main(String[] args) throws ClassNotFoundException, SQLException { con=ConnectionManager.getConnection(); con.setAutoCommit(false);//connection默认自动提交事务,false为不自动提交 con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); Statement stmt=con.createStatement(); int row=stmt.executeUpdate("insert into student(name,score,subject)values('李四',20,'数学')"); Savepoint savepoint=con.setSavepoint("first savePoint");//设置保存点 int row1=stmt.executeUpdate("insert into student(name,score,subject)values('王五',80,'哲学')"); con.rollback(savepoint);//回滚至保存点,在保存点之前的事务依旧提交数据持久化到数据库中,保存点之后的事务回滚,数据不会持久化 con.commit(); System.out.println("row:"+row); System.out.println("row1:"+row1); } }?