zoukankan      html  css  js  c++  java
  • java当中JDBC当中的transaction例子

    [学习笔记]

    7.jdbc的transaction例子:

    import java.sql.*;

    public class MySQlTransaction1 {

    public static void main(String[] args) throws SQLException {
    /*in my sql: create table Accounts(
    ID int(4) not null,
    NAME varchar(15),
    BALANCE int(4),
    primary key(ID)
    ) type=INNODB;
    insert into Accounts values(1,'wangwu',100);
    insert into Accounts values(3,'zhangsan',300);
    insert into Accounts values(4,'lisi',400);
    */
    Connection con = null;
    Statement s = null;
    try {
    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "1234");
    //s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
    /*by default, whenever execute a sql, it will commit automatically,
    public void setAutoCommit(boolean autoCommit) throws SQLException
    Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit
    mode, then all its SQL statements will be executed and committed as individual transactions.
    Otherwise, its SQL statements are grouped into transactions that are terminated by a call to
    either the method commit or the method rollback. By default, new connections are in
    auto-commit mode. */

    s = con.createStatement();

    s.executeUpdate("update ACCOUNTS set BALANCE=508 where ID=3");
    System.out.println("333333");
    /*下一步中本来应为where ID=4, 但是却误写成了www ID=4, 所以有错,所以到catch中,但rollback时
    , 却做不成功, 因为是autocommited模式,所以上一句ID=3,就做真改成508了。*/
    s.executeUpdate("update ACCOUNTS set BALANCE=608 www ID=4");
    System.out.println("444444");

    System.out.println("con = " + con);
    }
    catch (Exception e) {
    try{
    con.rollback();
    System.out.println("rollback successfully");
    }catch (Exception ex)
    {
    文章转载自原文:https://blog.csdn.net/qq_43650923/article/details/100653000

  • 相关阅读:
    2019.9.21 Tomcat基于端口的虚拟主机
    shell脚本作业
    DNS原理及其解析过程
    用户管理系统脚本
    pxe批量装机
    磁盘分区挂载脚本
    安装apache脚本
    linux远程拷贝命令及not a regular file 解决方案
    卸载虚拟网卡的方法
    watch的用法
  • 原文地址:https://www.cnblogs.com/haima1949/p/11490549.html
Copyright © 2011-2022 走看看