zoukankan      html  css  js  c++  java
  • 事物的一致性:向数据库中插入同一属性不同列的值,出现异常,致使出现异常前后,数据都无法插入

    主要是使用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);
    }
    }
    }

  • 相关阅读:
    UEFI和GPT
    EFI/UEFI BIOS 入门
    UEFI+GPT模式下的Windows系统中分区结构和默认分区大小及硬盘整数分区研究
    UEFI和Legacy及UEFI+Legacy启动的区别
    UEFI与MBR区别
    UI基础字典转模型
    UI基础九宫格
    UI基础UIView常见属性及方法
    UI基础控件UIButton
    OC中NSFileManager类 和 copy一些用法
  • 原文地址:https://www.cnblogs.com/lxnlxn/p/5773608.html
Copyright © 2011-2022 走看看