• JDBC事务(一)


    package cn.sasa.tran01;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class testJDBCTran {
    
        public static void main(String[] args) {
            Connection conn = null;
            PreparedStatement pstate = null;
            PreparedStatement pstate2 = null;
            try {
                //mysql的事务默认是自动执行的
                
                //注册驱动
                Class.forName("com.mysql.jdbc.Driver");
                
                //获得连接对象
                conn = DriverManager.getConnection("jdbc:mysql://192.168.0.207:3306/mydb", "root", "Console.Write21");
                
                //设置手动执行事务
                conn.setAutoCommit(false);
                
                //获得执行对象
                String sql = "insert into account (name,money) values ('aaaaaaaaaaaaaaaaaaa',200)";
                pstate = conn.prepareStatement(sql);
                //执行
                int rs = pstate.executeUpdate();
                
                String sql2 = "insert into account (name,money) values ('bb',300)";
                pstate2 = conn.prepareStatement(sql2);
                int rs2 = pstate2.executeUpdate();
                
                if(rs>0&&rs2>0) {
                    conn.commit();//提交事务
                    System.out.println("ok");
                }else {
                    conn.rollback();//回滚事务
                    System.out.println("-1");
                }
                
            }catch(Exception e) {
                try {
                    conn.rollback();
                    System.out.println("-2");
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }//回滚事务
            }finally {
                try {
                    if(pstate !=null) pstate.close();
                    if(pstate2 !=null) pstate2.close();
                    if(conn !=null) conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
  • 相关阅读:
    Python学习笔记 第四天
    Python学习笔记 第三天
    linux系统优化(CentOS7)
    ARMS踩坑合集
    zabbix报错合集(附解决方法)
    keepalived
    ansible
    nginx
    安装虚拟机
    linux发展、redhat与centos的区别
  • 原文地址:https://www.cnblogs.com/SasaL/p/10636756.html
Copyright © 2020-2023  润新知