用java代码对ACID的实现

来源:互联网 发布:linux服务器绑定域名 编辑:程序博客网 时间:2024/06/04 23:32


import org.junit.Test;


import jdbC.JdbcUtils;


public class demo {
public void money(String from ,String to,double money){
Connection con=null;
try {
//再操作同一个事物时用同一个connection
con=JdbcUtils.getConnection();//工具类得到connection对象
con.setAutoCommit(false);//设置为false
acid ac=new acid();//得到要修改的对象
ac.updataBlance(con,from,-money);//通过此方法对数据进行修改
ac.updataBlance(con,to, money);

con.commit();//完成修改成功
con.close();//connection对象关闭
} catch (Exception e) {
try {
con.rollback();//若失败的话执行此处,操作失败
con.close();//connection对象关闭
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
@Test
public void set(){
money("zs'", "ls", 100);//对数据进行验证

}

public class acid {
//演示转账的功能
public void updataBlance(Connection con,String name,double blance){//得到con对象,传入名字,传入修改的数据
try {


String sql="update account set balance=balance+? where name=?";//通过名字对名字所对应的数据进行修改
PreparedStatement statement=con.prepareStatement(sql);
statement.setDouble(1, blance);//设置数据
statement.setString(2, name);
statement.executeUpdate();//将数据进行跟新
} catch (Exception e) {
throw new RuntimeException();//抛出运行时期异常
}
}

0 0
原创粉丝点击