以下是使用事务教程中描述的提交和回滚的代码示例。

此示例代码是基于前面章节中完成的环境和数据库设置编写的。

复制并将以下示例代码保存到:CommitAndRollback.java 中,编译并运行如下 -

//STEP 1. Import required packages
// See more detail at http://www.yiibai.com/jdbc/ import java.sql.*; public class CommitAndRollback {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP"; // Database credentials
static final String USER = "root";
static final String PASS = "123456"; public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Set auto commit as false.
conn.setAutoCommit(false); //STEP 5: Execute a query to create statment with
// required arguments for RS example.
System.out.println("Creating statement...");
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE); //STEP 6: INSERT a row into Employees table
System.out.println("Inserting one row....");
String SQL = "INSERT INTO Employees " +
"VALUES (106, 28, 'Curry', 'Stephen')";
stmt.executeUpdate(SQL); //STEP 7: INSERT one more row into Employees table
SQL = "INSERT INTO Employees " +
"VALUES (107, 32, 'Kobe', 'Bryant')";
stmt.executeUpdate(SQL); //STEP 8: Commit data here.
System.out.println("Commiting data here....");
conn.commit(); //STEP 9: Now list all the available records.
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("List result set for reference....");
printRs(rs); //STEP 10: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
// If there is an error then rollback the changes.
System.out.println("Rolling back data here....");
try{
if(conn!=null)
conn.rollback();
}catch(SQLException se2){
se2.printStackTrace();
}//end try }catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main public static void printRs(ResultSet rs) throws SQLException{
//Ensure we start with first row
rs.beforeFirst();
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last"); //Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
System.out.println();
}//end printRs()
}//end JDBCExample
Java

编译并运行结果如下 -

F:\worksp\jdbc>javac -Djava.ext.dirs=F:\worksp\jdbc\libs CommitAndRollback.java

F:\worksp\jdbc>java -Djava.ext.dirs=F:\worksp\jdbc\libs CommitAndRollback
Connecting to database...
Thu Jun 01 02:30:04 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Creating statement...
Inserting one row....
Commiting data here....
List result set for reference....
ID: 100, Age: 28, First: Max, Last: Su
ID: 101, Age: 25, First: Wei, Last: Wang
ID: 102, Age: 35, First: Xueyou, Last: Zhang
ID: 103, Age: 30, First: Jack, Last: Ma
ID: 106, Age: 28, First: Curry, Last: Stephen
ID: 107, Age: 32, First: Kobe, Last: Bryant Goodbye! F:\worksp\jdbc>

JDBC事务提交/回滚实例的更多相关文章

  1. sql事务(Transaction)用法介绍及回滚实例

    sql事务(Transaction)用法介绍及回滚实例 事务(Transaction)是并发控制的单位,是用户定义的一个操作序列.这些操作要么都做,要么都不做,是一个不可分割的工作单位.通过事务, S ...

  2. spring5 源码深度解析----- 事务的回滚和提交(100%理解事务)

    上一篇文章讲解了获取事务,并且通过获取的connection设置只读.隔离级别等,这篇文章讲解剩下的事务的回滚和提交 回滚处理 之前已经完成了目标方法运行前的事务准备工作,而这些准备工作最大的目的无非 ...

  3. 难道你还不知道Spring之事务的回滚和提交的原理吗,这篇文章带你走进源码级别的解读。

    上一篇文章讲解了获取事务,并通过获取的connection设置只读,隔离级别等:这篇文章讲事务剩下的回滚和提交. 事务的回滚处理 之前已经完成了目标方法运行前的事务准备工作.而这些准备工作的最大目的无 ...

  4. 普通的jdbc事务在插入数据后 下面的代码报错时 数据不会回滚 但是 spring的事务会回滚

    普通的jdbc事务在插入数据后 下面的代码报错时 数据不会回滚 但是 spring的事务会回滚

  5. MockMvc 进行 controller层单元测试 事务自动回滚 完整实例

    package com.ieou.ms_backend.controller; import com.google.gson.Gson; import com.ieou.ms_backend.dto. ...

  6. spring + mybatis 注解式事务不回滚的原因分析 @Transactional

    在一个项目中发现spring的事务无法回滚. DEBUG: org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.ses ...

  7. MySql事务无法回滚的原因

    使用MySQL时.假设发现事务无法回滚,但Hibernate.Spring.JDBC等配置又没有明显问题时.不要苦恼,先看看MySQL创建的表有没有问题.即表的类型. InnoDB和MyISAM是在使 ...

  8. Spring事务不回滚原因分析

    Synchronized用于线程间的数据共享,而ThreadLocal则用于线程间的数据隔离. 在我完成一个项目的时候,遇到了一个Spring事务不回滚的问题,通过aspectJ和@Transacti ...

  9. Spring事务管理——回滚(rollback-for)控制

    探讨Spring事务控制中,异常触发事务回滚原理.文章进行了6种情况下的Spring事务是否回滚. 以下代码都是基于Spring与Mybatis整合,使用Spring声明式事务配置事务方法. 1.不捕 ...

随机推荐

  1. js中实现对checkbox选中和取消

    可以使用 element.attr('checked','checked') 来进行选中.但是不能使用 element.attr('checked','false') 来取消选中. 必须通过以下方式: ...

  2. HTML中Zen Coding

    嵌套运算符 嵌套运算符用于以缩写的方式安排元素在生成文档树中的位置:将其放在内部或成为相邻的元素. 子: > 可以使用 > 运算符指定嵌套元素在另一个元素内部: div>ul> ...

  3. 双系统linux+win之血的教训

    绝对不要用win的软件来直接调整linux分区!!!!! 除非你不想要这个linux分区里的数据了...

  4. 【C/C++】标准IO操作

    fwrite实现文件复制 //@ author 成鹏致远 //@ net http://infodown.tap.cn //@ qq 552158509 //@ blog lcw.cnblogs.co ...

  5. LeetCode: Binary Search Tree Iterator 解题报告

    Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...

  6. [转]Httrack工具与使用指南

    HTTrack工具介绍 HTTrack是一个网站镜像工具,本来是用来抓取网站做离线浏览用的.但是HTTrack的爬虫特性和搜索引擎蜘蛛爬虫非常的像,这也逐渐应用到 SEO(搜索引擎优化)工作中.其实这 ...

  7. 【转】oracle中的游标的原理和使用详解

    游标 游标的简介: 逐行处理查询结果,以编程的方式访问数据 游标的类型: 1,隐式游标:在 PL/SQL 程序中执行DML SQL 语句时自动创建隐式游标,名字固定叫sql. 2,显式游标:显式游标用 ...

  8. SpringBoot使用AutoConfiguration自定义Starter

    https://segmentfault.com/a/1190000011433487

  9. C语言 · 集合运算

    算法训练 集合运算   时间限制:1.0s   内存限制:512.0MB    问题描述 给出两个整数集合A.B,求出他们的交集.并集以及B在A中的余集. 输入格式 第一行为一个整数n,表示集合A中的 ...

  10. [shell]shell 中| && || () {} 用法以及shell的逻辑与或非

    转自:https://www.jianshu.com/p/617c1ee1e46e | 运算符 管道符号,是unix一个很强大的功能,符号为一条竖线:"|".用法: command ...