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

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

复制并将以下示例代码保存到: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. 关于 Nginx upstream keepalive 的说明

    模块是 HttpUpstreamModule,配置的一个例子: [shell]upstream http_backend {    server 127.0.0.1:8080; keepalive 1 ...

  2. [SQL in Azure] Configure a VNet to VNet Connection

    http://msdn.microsoft.com/en-us/library/azure/dn690122.aspx Configure a VNet to VNet Connection 2 ou ...

  3. [SQL in Azure] Tutorial: AlwaysOn Availability Groups in Azure (GUI)

    http://msdn.microsoft.com/en-us/library/azure/dn249504.aspx Tutorial: AlwaysOn Availability Groups i ...

  4. 每日英语:Marriage makes our children richer — Here's why

    Young people from less-privileged homes are more likely to graduate from college and earn more if ra ...

  5. 【C/C++】关于隐式转换·面试题分析

    题目 以下两个程序片段A 和B ,问哪个能进入循环? 片段A: unsigned short i; unsigned ; ; i < index-; i++) { ........ } 片段B: ...

  6. 【转】suspend造成死锁

    备注:我最近的项目就遇到了这个问题.只用了一个CCriticalSection对象,并且全部都有释放.但还是死活没查出死锁的原因.最后才发现原来是suspend导致的.最终用CEvent替代了susp ...

  7. weblogic迁移总结

    weblogic使用的数据库时DB2 1. 图形化安装weblogic和域,或者静默安装. 2. 查看环境变量env并修改,修改系统默认语言(根据实际情况) 3. 修改weblogic页面打开较慢问题 ...

  8. 2. 感知机(Perceptron)基本形式和对偶形式实现

    1. 感知机原理(Perceptron) 2. 感知机(Perceptron)基本形式和对偶形式实现 3. 支持向量机(SVM)拉格朗日对偶性(KKT) 4. 支持向量机(SVM)原理 5. 支持向量 ...

  9. 3. EM算法-高斯混合模型GMM

    1. EM算法-数学基础 2. EM算法-原理详解 3. EM算法-高斯混合模型GMM 4. EM算法-高斯混合模型GMM详细代码实现 5. EM算法-高斯混合模型GMM+Lasso 1. 前言 GM ...

  10. BI-LSTM-CRF在序列标注中的应用

    1. 前言 在NLP中有几个经典的序列标注问题,词性标注(POS),chunking和命名实体识别(NER).序列标注器的输出可用于另外的应用程序.例如,可以利用在用户搜索查询上训练的命名实体识别器来 ...