/** 文件名称:JDBCTestCase.java* 版权:Copyright 2006-2011 Huawei Tech. Co. Ltd. All Rights Reserved. * 描写叙述: JDBCTestCase.java* 改动人:z00106659* 改动时间:2011-12-2* 改动内容:新增*/
​
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
/*** 这个是一个简单演示JDBC操作的实例。相应胶片解说的七个操作步骤, 使用JDK 自带的Derby数据库;* * Derby 是由IBM捐献给Apache的DB项目的一个纯Java数据库,两种使用模式。 一种是作为嵌入式数据库,还有一种是作为网络数据库* * 此用例參考的Derby自带的Demo 在嵌入式 场景的使用有非常具体的凝视,在使用时降低安装数据库的麻烦。* * * @author z00106659* @version ONIP BME V300R001 2011-12-2* @since ONIP BME V300R001C00*/
public class JDBCTestCase {/*** 驱动类名称*/private String driver = "org.apache.derby.jdbc.EmbeddedDriver";/*** derby驱动协议头*/private String protocol = "jdbc:derby:";public static void main(String[] args) {new JDBCTestCase().go();System.out.println("SimpleApp finished");}@SuppressWarnings("unchecked")void go() {/* load the desired JDBC driver */loadDriver();/** We will be using Statement and PreparedStatement objects for* executing SQL. These objects, as well as Connections and ResultSets,* are resources that should be released explicitly after use, hence the* try-catch-finally pattern used below. We are storing the Statement* and Prepared statement object references in an array list for* convenience.*/Connection conn = null;/** This ArrayList usage may cause a warning when compiling this class* with a compiler for J2SE 5.0 or newer. We are not using generics* because we want the source to support J2SE 1.4.2 environments.*/ArrayList statements = new ArrayList(); // list of Statements,// PreparedStatementsPreparedStatement psInsert = null;PreparedStatement psUpdate = null;PreparedStatement psDelete = null;Statement s = null;ResultSet rs = null;try {Properties props = new Properties(); // connection properties// providing a user name and password is optional in the embedded// and derbyclient frameworksprops.put("user", "user1");props.put("password", "user1");String dbName = "derbyDB"; // the name of the databaseconn = DriverManager.getConnection(protocol + dbName+ ";create=true", props);System.out.println("Connected to and created database " + dbName);// We want to control transactions manually. Autocommit is on by// default in JDBC./*** 支持事物*/conn.setAutoCommit(false);/** Creating a statement object that we can use for running various* SQL statements commands against the database.*/s = conn.createStatement();statements.add(s);// We create a table...s.execute("create table location(num int, addr varchar(40))");System.out.println("Created table location");// and add a few rows...psInsert = conn.prepareStatement("insert into location values (?, ?

)"); statements.add(psInsert); psInsert.setInt(1, 2014); psInsert.setString(2, "zhangyaun"); psInsert.executeUpdate(); psInsert.setInt(1, 1956); psInsert.setString(2, "Webster St."); psInsert.executeUpdate(); System.out.println("Inserted 1956 Webster"); psInsert.setInt(1, 180); psInsert.setString(2, "Union St."); psInsert.executeUpdate(); System.out.println("Inserted 1910 Union"); conn.commit();//这里将操作提交 // Let's update some rows as well... // parameter 1 and 3 are num (int), parameter 2 is addr (varchar) try { psDelete = conn .prepareStatement("delete from location where num=?"); statements.add(psDelete); psDelete.setInt(1, 2014); psDelete.executeUpdate(); conn.rollback();//这里回滚。能够将删除的2014 回滚回来 } catch (RuntimeException e1) { e1.printStackTrace(); } psUpdate = conn .prepareStatement("update location set num=?, addr=?

where num=?

"); statements.add(psUpdate); psUpdate.setInt(1, 180); psUpdate.setString(2, "Grand Ave."); psUpdate.setInt(3, 1956); psUpdate.executeUpdate(); System.out.println("Updated 1956 Webster to 180 Grand"); conn.commit(); try { psUpdate.setInt(1, 300); psUpdate.setString(2, "Lakeshore Ave."); psUpdate.setInt(3, 180); psUpdate.executeUpdate(); System.out.println("Updated 180 Grand to 300 Lakeshore"); conn.commit(); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * We select the rows and verify the results. */ rs = s.executeQuery("SELECT num, addr FROM location ORDER BY num"); while (rs.next()) { System.out.println(rs.getInt(1)); } int number; // street number retrieved from the database boolean failure = false; if (!failure) { System.out.println("Verified the rows"); } // delete the table s.execute("drop table location"); System.out.println("Dropped table location"); /* * We commit the transaction. Any changes will be persisted to the * database now. */ conn.commit(); System.out.println("Committed the transaction"); try { // the shutdown=true attribute shuts down Derby DriverManager.getConnection("jdbc:derby:;shutdown=true"); // To shut down a specific database only, but keep the // engine running (for example for connecting to other // databases), specify a database in the connection URL: // DriverManager.getConnection("jdbc:derby:" + dbName + // ";shutdown=true"); } catch (SQLException se) { if (((se.getErrorCode() == 50000) && ("XJ015".equals(se .getSQLState())))) { // we got the expected exception System.out.println("Derby shut down normally"); // Note that for single database shutdown, the expected // SQL state is "08006", and the error code is 45000. } else { // if the error code or SQLState is different, we have // an unexpected exception (shutdown failed) System.err.println("Derby did not shut down normally"); printSQLException(se); } } } catch (SQLException sqle) { printSQLException(sqle); } finally { // release all open resources to avoid unnecessary memory usage // ResultSet try { if (rs != null) { rs.close(); rs = null; } } catch (SQLException sqle) { printSQLException(sqle); } // Statements and PreparedStatements int i = 0; while (!statements.isEmpty()) { // PreparedStatement extend Statement Statement st = (Statement) statements.remove(i); try { if (st != null) { st.close(); st = null; } } catch (SQLException sqle) { printSQLException(sqle); } } // Connection try { if (conn != null) { conn.close(); conn = null; } } catch (SQLException sqle) { printSQLException(sqle); } } } /** * Reports a data verification failure to System.err with the given message. * * @param message * A message describing what failed. */ private void reportFailure(String message) { System.err.println("\nData verification failed:"); System.err.println('\t' + message); } /** * Prints details of an SQLException chain to <code>System.err</code>. * Details included are SQL State, Error code, Exception message. * * @param e * the SQLException from which to print details. */ public static void printSQLException(SQLException e) { // Unwraps the entire exception chain to unveil the real cause of the // Exception. while (e != null) { System.err.println("\n----- SQLException -----"); System.err.println(" SQL State: " + e.getSQLState()); System.err.println(" Error Code: " + e.getErrorCode()); System.err.println(" Message: " + e.getMessage()); // for stack traces, refer to derby.log or uncomment this: // e.printStackTrace(System.err); e = e.getNextException(); } } /** * Loads the appropriate JDBC driver for this environment/framework. For * example, if we are in an embedded environment, we load Derby's embedded * Driver, <code>org.apache.derby.jdbc.EmbeddedDriver</code>. */ private void loadDriver() { try { Class.forName(driver).newInstance(); System.out.println("Loaded the appropriate driver"); } catch (ClassNotFoundException cnfe) { System.err.println("\nUnable to load the JDBC driver " + driver); System.err.println("Please check your CLASSPATH."); cnfe.printStackTrace(System.err); } catch (InstantiationException ie) { System.err.println("\nUnable to instantiate the JDBC driver " + driver); ie.printStackTrace(System.err); } catch (IllegalAccessException iae) { System.err.println("\nNot allowed to access the JDBC driver " + driver); iae.printStackTrace(System.err); } } }

实现数据库事务

首先设置:

conn.setAutoCommit(false);

在commit()方法和rollback方法之间的操作会被回滚。我们做实验:

conn.commit();//这里将操作提交// Let's update some rows as well...// parameter 1 and 3 are num (int), parameter 2 is addr (varchar)try {psDelete = conn.prepareStatement("delete from location where num=?");statements.add(psDelete);psDelete.setInt(1, 2014);psDelete.executeUpdate();conn.rollback();//这里回滚,能够将删除的2014 回滚回来

这时删除的2014将回滚回来。回滚一般用于发生异常时,因此一般能够写在catch中,当删除不存在的编号时。回滚就起作用了。

转载于:https://www.cnblogs.com/wzzkaifa/p/7101356.html

上机题目(0基础)- 数据库事务(Java)相关推荐

  1. 0基础如何自学Java(从入门到精通)

    如果你想自学 Java,认真看完本文,你以后的职场生涯至少少走1年弯路. 行业现状 ==== 程序员现状 由于程序员的薪水比较高,最近几年有很多其他专业的人涌进了程序员行业,加速了这个行业的内卷,但是 ...

  2. 0基础小白学好JAVA的5个方法

    JAVA分两个大方向web企业级开发(JavaWeb J2EE)和手机android开发.一般从事Java的开发人员都会从J2SE开始学习,因此对于J2SE的掌握必须要牢固.然而在初期学习时,通常会对 ...

  3. java 获取文件所在的文件夹_带你0基础编写一个Java小程序,领略Java程序从编写到编译再到运行的全流程...

    在学习Java之前我们需要先认识下什么是计算机语言?计算机语言又有哪些分类?在了解这些后对我们理解学习帮助是很大的. 要知道计算机语言是人与计算机之间进行信息交流沟通的一种特殊语言,又分为机械语言.汇 ...

  4. 0基础学java有多难?自学Java和参加培训学Java的难易度对比分析!

    在一些知识问答平台上,我看到有很多在问"0基础学java有多难",如果你想0基础自学Java那可能会比较困难,但是如果选择报培训班进行学习,即便是0基础,学Java其实也并不难.所 ...

  5. 【0基础学java】教学日志:javaSE-面向对象6-面向对象前4章上机作业点评,主要涉及继承、封装、多态三个章节的内容

    目录 一.面向对象第一章上机作业参考答案(略) 二.面向对象第二章上机作业参考答案: 三.面向对象第三章上机作业参考答案: 1.上机练习1已在第三章博客中编写,请参考: 2.上机练习2 四.面向对象第 ...

  6. 0 基础 Java 自学之路(2022年最新版)

    这是专门针对小白的零基础Java教程. 为什么要学Java? 因为Java是全球排名第一的编程语言,Java工程师也是市场需求最大的软件工程师,选择Java,就是选择了高薪. 为什么Java应用最广泛 ...

  7. java mysql数据库回退_数据库事务及Java中的处理

    事 务是指一组相互依赖的操作行为,举一个举得不能再被举的例子就是银行交易,当然还有其他像网上购物,电子货币交易等等,事务的成功取决于这些相互依赖的操 作行为是否都能执行成功,只要有一个操作行为失败,就 ...

  8. Spring JDBC-Spring事务管理之数据库事务基础知识

    概述 数据库事务的概念 原子性 一致性 隔离性 持久性 数据并发的问题 脏读dirty read 不可重复读unrepeatable read 幻象读 phantom read 幻象读和不可重复度的区 ...

  9. 数据库事务系列-事务模型基础

    从这篇文章开始,笔者将会在接下来很长时间里整理记录一个相对独立的知识领域-数据库事务,之所以忽然有这个想法,说来也是一种机缘巧合.本来是单纯计划写写HBase行级事务模型的具体实现的,但是在周末一不小 ...

最新文章

  1. undertale人物_【undertale】传说之下精美人物图包 (Frisk篇)
  2. PHP如何使用GeoIP数据库
  3. winform界面嵌入dwg图纸_c# cad中插入另一个dwg的图块
  4. 一天学完spark的Scala基础语法教程七、数组(idea版本)
  5. 常用计算机二级函数,计算机二级MS office常用函数
  6. Vue页面骨架屏(一)
  7. java 图片合成 红色失真_Java - 处理某些图片泛红
  8. BZOJ 1567: [JSOI2008]Blue Mary的战役地图
  9. Gdevops广州站:大咖齐聚,从事运维和数据库的你不能错过!
  10. linux 生成随机数 命令,Linux生成随机数的多种方法
  11. Java常见面试题收集
  12. Windows10安装 virtualbox虚拟机
  13. eclipse安装 环境变量配置
  14. 布料仿真先导2-带阻尼的单个小球单摆下的拉格朗日方程列些和matlab仿真
  15. sql server windows nt 64bit 内存占用过高
  16. 软考信息系统项目管理师考试心得-备考
  17. android4.4中添加方案,Android4.0-4.4 添加实体按键振动支持的方法(java + smali版本)
  18. 硬件配置部分——从无到有自主搭建视觉惯性VI-SLAM(vins-mono)平台
  19. CF794E Choosing Carrot
  20. 深耕核心技术·赋能数字化转型 ——大快搜索黑科技亮相2019(第四届)大数据产业生态大会,斩获多项大奖...

热门文章

  1. 大数据处理时用到maven的repository
  2. 我是怎样成长为系统架构师的
  3. CSU 1325: A very hard problem 中南月赛的一道题。
  4. Nginx负载均衡+tomcat+session共享
  5. 面性对象中栈内存和堆内存的理解
  6. 如何使wordpress导航栏在新窗口打开
  7. [转]线程安全 c/c++
  8. 遇到奇怪的C#/C/C++或者Java的bug可以去问问Coverity
  9. Android开发之LisitView的图文并排效果实现(源代码分享)
  10. Camera初探(二)