一,最近项目中,spring事物的管理,引发好奇,就是在事物回滚之前,对数据的插入更新操作,只要
未提交,都不更改数据库,但是在查询时得到的结果却是插入更新之后的,带着疑问我做一下的
例子.
二,JDBCHelper类
class="java" name="code">package com.ming.test.two;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCHelper {
public static ThreadLocal<Connection> local = new ThreadLocal<Connection>();
//启动时 加载驱动
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("mysql驱动不存在!");
}
}
public static Connection getConnection(){
Connection connection = local.get();//在当前线程找
try {
if(connection==null){
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull", "root","root");
local.set(connection);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("connection获取失败!");
}
return connection;
}
public static void closeConnection(Connection connection ){
try {
if(connection!=null){
connection.close();
local.remove();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
test类
package com.ming.test.two;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test {
public static String id="12";
public static void main(String[] args) {
Connection con = JDBCHelper.getConnection();
try {
// con.createStatement();
// con.prepareStatement("");
con.setAutoCommit(false);//现将事物自动提交设为false
con.setTransactionIsolation(con.TRANSACTION_READ_COMMITTED);
PreparedStatement p = con.prepareStatement("insert into account(accountId,id,username) values("+id+",1,'jacky"+id+"')");
p.execute();
//con.prepareStatement("select * from account where accountId=7");
PreparedStatement p1 = con.prepareStatement("select * from account where accountId="+id);
ResultSet set = p1.executeQuery();
while(set.next()){
System.out.println(set.getRow()+"-"+set.getString(1)+"-"+set.getString(2)+"-"+set.getString(3));
}
int i =1/0;
con.commit();//提交
} catch (Exception e) {
System.out.println("exception");
// TODO Auto-generated catch block
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
三,结论以及注意
注意事项:autocommot必须设置为false;
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException : Can't call rollback when autocommit=true
而且
异常的发生必须是在commit之前,否则也失效的.
结论就是,在事物回滚时,所有的更新新增操作都是无效,但是在con查询中这些都是最新影响的数据。