事物的一致性:向数据库中插入同一属性不同列的值,出现异常,致使出现异常前后,数据都无法插入

主要是使用connection的三个方法实现:

开始事物:取消默认提交:connection.setAutoCommit(false);//其可选择false和true

都成功提交事物:connection.commit();

回滚事物:connection.rollback();

---------------------------------------------------------------------------------------------------------------

package com.lanqiao.javatest;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.junit.Test;

import com.mysql.jdbc.Statement;

public class TestT {
static Test12 t=new Test12();
static Test1 t1=new Test1();
/*
* 事物的一致性,多个操作,每个使用自己的链接无法保证一致性,
* 即无法同一属性都插入或都删除值,而出现异常之后,异常前面的输入,异常后面没有输入,
* */
@Test
//例子
public void updateT() throws Exception{
Connection connection=null;
PreparedStatement preparedStatement=null;

try {
connection=t1.getConnection();

//开始事物:取消默认提交
connection.setAutoCommit(false);//其可选择false和true
//两个事物操作:
String sql="update test set grade= grade+100 where flow_id=2";
update(connection, sql);

//此处出现异常
int i=10/0;
System.out.println(i);

String sql1="update test set grade= grade+100 where flow_id=3";
update(connection, sql1);

//都成功提交事物
connection.commit();
} catch (Exception e) {
e.printStackTrace();
try {//回滚事物
connection.rollback();
} catch (Exception e2) {
e.printStackTrace();
}
}finally {
//关闭资源的方法
t.close(connection, preparedStatement, null);
}
}
public void update(Connection connection,String sql,Object...args) throws Exception{
//Object...args:可变参数,可以当数组使用,不用知道他的大小,直接传就行了
//数据库只连接一次
PreparedStatement preparedStatement=null;
try {
preparedStatement=connection.prepareStatement(sql);

for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
//更新
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
t.close(connection, preparedStatement, null);
}
}
}

 

posted @ 2016-08-15 17:02  G-&-D  阅读(330)  评论(0编辑  收藏  举报