zoukankan      html  css  js  c++  java
  • jdbc事务

    package jdbc;

    import org.junit.Test;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Collection;

    public class Test3 {
    @Test
    public void test() {
    //配置信息
    String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=PRC";
    String username = "root";
    String password = "";

    Connection conn = null;
    //加载驱动
    try {
    Class.forName("com.mysql.cj.jdbc.Driver");
    //连接数据库,代表数据库
    conn = DriverManager.getConnection(url,username,password);
    //通知数据库开启事务,false 开启
    conn.setAutoCommit(false);
    String sql = "update account set money = money-100 where name = '王五'";
    conn.prepareStatement(sql).executeUpdate();
    //制作错误
    //int i = 1/0;

    String sql2 = "update account set money = money+200 where name = '张三'";
    conn.prepareStatement(sql2).executeUpdate();
    conn.commit();//以上2条sql都执行成功了,就提交事务!
    System.out.println("success");
    } catch (Exception e) {
    try {
    //如果出现异常,就通知数据库回滚事务
    conn.rollback();
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    e.printStackTrace();
    }finally {
    try {
    conn.close();
    } catch (SQLException throwables) {
    throwables.printStackTrace();
    }
    }
    }
    }
  • 相关阅读:
    20151224--
    20151223--联系人项目
    20151222--Ajax三级无刷新
    20151221--三级有刷新联动
    20151220--导航前四问已解答
    递归
    Request和Response详解
    无刷新三级联动查询
    20151219--导航自己制作的一部分
    151030
  • 原文地址:https://www.cnblogs.com/liuyunche/p/14148022.html
Copyright © 2011-2022 走看看