标签:
@Test
public void test_trans(){
try {
Class .forName( "com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection( url, user, password);
connection .setAutoCommit( false);//设置不默认开启事物
PreparedStatement ps = connection.prepareStatement( "update
test set name=‘000‘ where id=1");
ps .executeUpdate();
int i = 1 /0; //错误
ps = connection. prepareStatement("update
test set name=‘222‘ where id=2");
ps .executeUpdate();
connection .commit(); //事物提交
} catch (Exception e) {
e .printStackTrace();
try {
connection.rollback ();//事物回滚
} catch (SQLException e1) {
e1 .printStackTrace();
}
}finally {
//关闭资源
}
}
|
@Test
public void test_trans1(){
Savepoint sp = null;
try {
Class .forName( "com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection( url, user, password);
connection .setAutoCommit( false);//设置不默认开启事物
PreparedStatement ps = connection.prepareStatement( "update
test set name=‘000‘ where id=1");
ps .executeUpdate();
sp = connection. setSavepoint();//设置回滚点
int i = 1 /0; //错误
ps = connection. prepareStatement("update
test set name=‘222‘ where id=2");
ps .executeUpdate();
} catch (Exception e) {
e .printStackTrace();
try {
connection.rollback (sp); //事物回滚
} catch (SQLException e1) {
e1 .printStackTrace();
}
}finally {
try {
connection.commit ();
} catch (SQLException e) {
e .printStackTrace();
}//事物提交
//关闭资源
}
}
|
TRANSACTION_READ_UNCOMMITTED 指示可以发生脏读 (dirty read)、不可重复读和虚读 (phantom read) 的常量。 |
TRANSACTION_READ_COMMITTED 指示不可以发生脏读的常量;不可重复读和虚读可以发生。 |
TRANSACTION_REPEATABLE_READ 指示不可以发生脏读和不可重复读的常量;虚读可以发生。 |
TRANSACTION_SERIALIZABLE 指示不可以发生脏读、不可重复读和虚读的常量。 |
java.sql.Connection | ||
---|---|---|
public static final int |
TRANSACTION_READ_COMMITTED |
2 |
public static final int |
TRANSACTION_READ_UNCOMMITTED |
1 |
public static final int |
TRANSACTION_REPEATABLE_READ |
4 |
public static final int |
TRANSACTION_SERIALIZABLE |
8 |
在事务管理中违反ACID特性的3个问题:脏读取、不可重复读和幻影行。如果存在多个并发的事务在运行,而这些事务操作了同一个数据来完成他们的任务,就会导致3个问题的存在。要解决它们,就必须在事务之间定义合适的隔离级别。事务之间存在的3个问题是:
脏读取 (Dirty read)
当一个事务读取了另一个事务尚未提交的更新,就叫脏读取。在另一个事务回滚的情况下,当前事务所读取的另一个事务的数据就是无效的。
不可重复读取(Nonrepeatable read)
在一个事务中执行多次同样的查询操作,但每次查询的结果都不一样,就叫做不可重复读取,通常这种情况是由于数据在二次查询之间被另一个并发的事务所修改。
幻读(Phantom rows)
这是对事务危害最小的一个问候,它类似不可重复读取,也是一个事务的更新结果影响到另一个事务问题。但是它不仅影响另一个事务查询结果,而且还会使查询语句返回一些不同的行录行。
这3个问题危害程度依次为:脏读取最大、不可重复读取其次、幻读最小。
标签:
原文地址:http://blog.csdn.net/javastudyr/article/details/42647175