事务特征:原子性,一致性,独立性,持久性。

要想操作事务,必须按照以下步骤完成。

1,取消掉自动提交(SET AUTOCOMMIT=0):每次执行数据库更新的时候实际上发出SQL命令之后就已经提交上去了。

2,开始事务,

3,进行一系列操作

4,如果操作一切合格,则提交事务,

5,如果发现一个地方有问题,则可以回滚,

6,或者设置一个SAVEPOINT保存事务提交点。

在JDBC中,同样支持事务的处理操作。

一,不使用事务处理情况。

通过批处理插入数据:

package 类集;
import java.sql.Connection ;
import java.sql.DriverManager ;
import java.sql.Statement ;
public class TranDemo01{
// 定义MySQL的数据库驱动程序
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
// 定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/sys" ;
// MySQL数据库的连接用户名
public static final String DBUSER = "root" ;
// MySQL数据库的连接密码
public static final String DBPASS = "aaaaaa" ;
public static void main(String args[]) throws Exception{ // 所有异常抛出
Connection conn = null ; // 数据库连接
Statement stmt = null ; // 定义数据库操作
Class.forName(DBDRIVER) ; // 加载驱动程序
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
stmt = conn.createStatement() ;
stmt.addBatch("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-1',11,'1975-03-05') ") ;
stmt.addBatch("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-2',12,'1976-03-05') ") ;
// 加入“'”之后,此SQL语法就出现了错误,所以,肯定执行到此语句的时候出现代码错误
stmt.addBatch("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-'3',13,'1977-06-01') ") ;
stmt.addBatch("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-4',14,'1965-03-05') ") ;
int temp[] = stmt.executeBatch() ;  //返回更新数据量
System.out.println("更新了:" + temp.length+ "条数据。") ;
stmt.close() ;
conn.close() ; // 数据库关闭
}
};

运行结果:

Sun Apr 23 00:09:39 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.
Exception in thread "main" java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3',13,'1977-06-01')' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createBatchUpdateException(SQLError.java:1162)
at com.mysql.jdbc.StatementImpl.executeBatchInternal(StatementImpl.java:1048)
at com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:958)
at 类集.TranDemo01.main(TranDemo01.java:29)

查询数据库:

发现,虽然程序报错了,但是批处理中其他语句却执行成功了。

以上操作只将错误数据空出,如果这5条记录有相互关系,则这样实现肯定不符合要求。

JDBC事务处理操作步骤

事务处理代码:

package 类集;
import java.sql.Connection ;
import java.sql.DriverManager ;
import java.sql.SQLException ;
import java.sql.Statement ;
public class TranDemo02{
// 定义MySQL的数据库驱动程序
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
// 定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/sys" ;
// MySQL数据库的连接用户名
public static final String DBUSER = "root" ;
// MySQL数据库的连接密码
public static final String DBPASS = "aaaaaa" ;
public static void main(String args[]) throws Exception{ // 所有异常抛出
Connection conn = null ; // 数据库连接
Statement stmt = null ; // 定义数据库操作
Class.forName(DBDRIVER) ; // 加载驱动程序
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ; conn.setAutoCommit(false) ; // 取消掉自动提交

stmt =
conn.createStatement() ;
stmt.addBatch
("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-1',11,'1975-03-05') ") ;
stmt.addBatch("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-2',12,'1976-03-05') ") ;
// 加入“'”之后,此SQL语法就出现了错误,所以,肯定执行到此语句的时候出现代码错误
stmt.addBatch("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-'3',13,'1977-06-01') ") ;
stmt.addBatch("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-4',14,'1965-03-05') ") ;
try{
int temp[] = stmt.executeBatch() ;
System.out.println("更新了:" + temp.length+ "条数据。") ;
conn.commit() ; // 所有的操作成功了
}catch(Exception e){
try
{
conn.rollback() ;

          System.out.println("数据更新失败");
}catch(Exception e1){ }
}
stmt.close() ;
conn.close() ; // 数据库关闭
}
};

运行结果:

Sun Apr 23 00:20:38 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.
数据更新失败

数据库查询:

可以发现并没有插入为报错的数据。

SAVEPOINT:

正常情况下,可以通过SAVEPOINT保存事务的操作点,默认情况下,回滚是将所有操作取消掉,而通过SAVEPOINT可以设置回退的位置。

一个Sessions的操作(每一个连接到数据库上的用户都称为一个Session)

操作1,

操作2

操作3,

SAVEPOINT 记录点1

操作4

操作5

RALLBACK 记录点1.

设置SAVEPOINT

 Savepoint setSavepoint()
在当前事务中创建一个未命名的保存点 (savepoint),并返回表示它的新 Savepoint 对象。

实例代码:

package 类集;
import java.sql.Connection ;
import java.sql.DriverManager ;
import java.sql.SQLException ;
import java.sql.Statement ;
import java.sql.Savepoint ;
public class TranDemo03{
// 定义MySQL的数据库驱动程序
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
// 定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/sys" ;
// MySQL数据库的连接用户名
public static final String DBUSER = "root" ;
// MySQL数据库的连接密码
public static final String DBPASS = "aaaaaa" ;
public static void main(String args[]) throws Exception{ // 所有异常抛出
Connection conn = null ; // 数据库连接
Statement stmt = null ; // 定义数据库操作
Class.forName(DBDRIVER) ; // 加载驱动程序
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ; conn.setAutoCommit(false) ; // 取消掉自动提交 stmt = conn.createStatement() ;
stmt.executeUpdate("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-1',11,'1975-03-05') ") ;
stmt.executeUpdate("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-2',12,'1976-03-05') ") ;
Savepoint sp = conn.setSavepoint() ; // 设置保存点 stmt.executeUpdate("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-4',14,'1965-03-05') ") ;
stmt.executeUpdate("INSERT INTO user(name,age,birthday)" +
" VALUES ('LXH-5',15,'1965-08-05') ") ;
try{
conn.rollback(sp) ; // 回滚到保存点
conn.commit() ; // 所有的操作成功了
       System.out.println("程序出错,已经回滚到保存点。");
}catch(Exception e){
e.printStackTrace() ;
}
stmt.close() ;
conn.close() ; // 数据库关闭
}
};

程序结果:

Sun Apr 23 00:34:43 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.
程序出错,已经回滚到保存点。

数据库查询:

可以发现,因为发生错误,所以发生回滚,回滚到保存点,保存点之前的数据都正常更新,之后的数据没有正常插入。

总结

事务的基本概念

如果数据库中处理事务

处理事务的步骤:1,取消提交,2,执行多条SQL语句。3,如果没有异常就提交事务。否则回滚。

保存点很少使用。

JDBC:数据库操作:事务的更多相关文章

  1. JDBC数据库操作

    JDBC:   创建SQL语句对象    Statement statement = (Statement) con.createStatement() ;   调用执行     statement. ...

  2. [总结] JDBC数据库操作

    1.加载驱动--告诉驱动管理将使用哪一个数据库的驱动包. class.forName("com.mysql.jdbc.Driver"); 2.操作JDBC ADI完成数据库动作 D ...

  3. java jdbc数据库操作

    package shb.java.demo3; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQ ...

  4. 浅谈.net中数据库操作事务

    .net中的事务 关键几点 概念:1:什么是事务 2:什么时候用事务 3:基本的语法 (1): 事务(Transaction)是访问并可能更新数据库中各种数据项的一个程序执行单元(unit).事务通常 ...

  5. JDBC:数据库操作:BLOB数据处理

    CLOB主要保存海量文字,而BLOB是专门保存二进制数据:包括,图片,音乐,影片.等. 在MYSQL中,BLOB类型使用LONGBLOB声明,最高可存储4G内容. 创建一个表: create tabl ...

  6. JDBC:数据库操作:处理大对象CLOB数据

    目标: 了解大对象处理基本原理, 掌握CLOB数据的读,写操作. 可以使用CLOB类处理大文本数据. 大对象处理主要指CLOB和BLOB两种类型字段.可以大量存储文字. 要想在程序中处理这样的大数据操 ...

  7. 使用TransactionScope(轻量级事务)实现数据库操作事务

    TransactionScope是.Net Framework 2.0滞后,新增了一个名称空间.它的用途是为数据库访问提供了一个"轻量级"[区别于:SqlTransaction]的 ...

  8. Codeigniter 数据库操作事务情况下获取不到last_insert_id()

    开发中,数据库Insert使用了事务,如果 $this->db->insert_id() 放在 $this->db->trans_complete(); 这句语句之后,$thi ...

  9. 数据库操作事务IsolationLevel 枚举

      成员名称 说明   Chaos 无法覆盖隔离级别更高的事务中的挂起的更改.   ReadCommitted 在正在读取数据时保持共享锁,以避免脏读,但是在事务结束之前可以更改数据,从而导致不可重复 ...

随机推荐

  1. hdu 1011(Starship Troopers,树形dp)

    Starship Troopers Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...

  2. 【BZOJ 1697】1697: [Usaco2007 Feb]Cow Sorting牛排序

    1697: [Usaco2007 Feb]Cow Sorting牛排序 Description 农夫JOHN准备把他的 N(1 <= N <= 10,000)头牛排队以便于行动.因为脾气大 ...

  3. VB 中DTpicker日期控件的运用

    1.如何加载 VB默认的控件栏中是没有DTpicker日期控件的,添加过程:工具--部件--控件--"Microsoft  Windows Common Controls-2.6.0&quo ...

  4. hdu 4489 The King’s Ups and Downs(基础dp)

    The King’s Ups and Downs Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java ...

  5. 【树形dp】The more, The Better

    [HDU1561]The more, The Better Time Limit: 6000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K ...

  6. 【贪心】【堆】Gym - 101128C - Canvas Painting

    一些画布,每块有其大小,一开始都是白的,你任意将它们排序,然后一次操作可以选择一段连续的相同颜色的画布,从中任选一个位置,左侧涂上任意一种颜色,右侧涂上另一种.消耗是这一段画布的总的大小.问你要将所有 ...

  7. Jedis笔记

    Sting: Jedis jedis=RedisClient.getResource(); jedis.set("hello", "world"); Syste ...

  8. Windows下编译protobuf v3.3.0

    一:概述 关于 protobuf 在此不再多说,此处记录下成功编译步骤以备日后查阅.注意:本文并不是使用cmake gui进行编译的,如果熟悉cmake gui的话,也可以使用gui进行生成编译. 二 ...

  9. Educational Codeforces Round 8 A. Tennis Tournament 暴力

    A. Tennis Tournament 题目连接: http://www.codeforces.com/contest/628/problem/A Description A tennis tour ...

  10. Unity3D 避免玩家作弊

    如果你的Unity项目快上线了,我强烈建议你看一下Anti-Cheat这个插件.因为IOS和Android分别越狱和Root后玩家可以使用 @八门神器 @烧饼修改器 等一些列作弊的软件来修改游戏内存, ...