当设置jdbc事务自动提交为false时,且事务没有提交,在数据库里查找是不会发现变化的,但是像jdbc中的一些方法如executeUpdate、executeQuery是会返回结果的。下面一个例子,同一事务做了两次更新,会相互影响的,但是只要没提交,数据库中是不会发生变化的
package x.y.transaction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import junit.framework.TestCase;
public class TransTest extends TestCase {
private Connection con = null;
@Override
public void setUp(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:test", "h", "1");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testUpdate(){
// assertNotNull(con);
PreparedStatement ps = null;
try {
con.setAutoCommit(false);
ps = con.prepareStatement("update person set id=? where id=?");
ps.setInt(1, 3);
ps.setInt(2, 1);
int rows = ps.executeUpdate();
System.out.println("rows:"+rows);//注意事务没有提交
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(ps != null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Test
public void testTwoUpdates(){
testUpdate();//输出1
testUpdate();//输出0
}
转载于:https://blog.51cto.com/leopold/1181424