/*
* 文件名称: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,
// PreparedStatements
PreparedStatement 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 frameworks
props.put("user", "user1");
props.put("password", "user1"); String dbName = "derbyDB"; // the name of the database conn = 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中,当删除不存在的编号时。回滚就起作用了。

上机题目(0基础)- 数据库事务(Java)的更多相关文章

  1. SpringBoot2.0 基础案例(09):集成JPA持久层框架,简化数据库操作

    一.JAP框架简介 JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范.主要是为了简化持久层开发以及整合ORM技术,结束H ...

  2. 阿里P7整理“硬核”面试文档:Java基础+数据库+算法+框架技术等

    现在的程序员越来越多,大部分的程序员都想着自己能够进入大厂工作,但每个人的能力都是有差距的,所以并不是人人都能跨进BATJ.即使如此,但身在职场的我们一刻也不能懈怠,既然对BATJ好奇,那么就要朝这个 ...

  3. JAVA思维导图系列:多线程0基础

    感觉自己JAVA基础太差了,又一次看一遍,已思维导图的方式记录下来 多线程0基础 进程 独立性 拥有独立资源 独立的地址 无授权其它进程无法訪问 动态性 与程序的差别是:进程是动态的指令集合,而程序是 ...

  4. JDBC基础学习(四)—数据库事务

    一.事务基本认识 1.事务的概述      为了保证数据库中数据的一致性,数据的操作应当是离散的成组的逻辑单元.当它全部完成时,数据的一致性可以保持,而当这个单元中的一部分操作失败,整个事务应当全部视 ...

  5. 0基础的小白怎么学习Java?

    自身零基础,那么我们应该先学好Java,首先我们来了解下Java的特性: Java语言是简单的 Java语言的语法与C语言和C++语言很接近,使得大多数程序员很容易学习和使用Java.另一方面,Jav ...

  6. Java 入门课程视频实战-0基础 上线了,猜拳游戏,ATM实战,欢迎围观

    Java 入门课程视频实战-0基础 已经上传完了.欢迎小伙伴们过来围观 直接进入: http://edu.csdn.net/course/detail/196 课程文件夹例如以下: 1 初识Java  ...

  7. SpringBoot2.0 基础案例(12):基于转账案例,演示事务管理操作

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.事务管理简介 1.事务基本概念 一组业务操作ABCD,要么全部 ...

  8. _00017 Kafka的体系结构介绍以及Kafka入门案例(0基础案例+Java API的使用)

    博文作者:妳那伊抹微笑 itdog8 地址链接 : http://www.itdog8.com(个人链接) 博客地址:http://blog.csdn.net/u012185296 博文标题:_000 ...

  9. Spring学习记录5——数据库事务基础知识

    何为数据库事务 “一荣共荣,一损共损”这句话很能体现事务的思想,很多复杂的事务要分步进行,但它们组成了一个整体,要么整体生效,要么整体失效.这种思想反映到数据库上,就是多条SQL语句,要么全部成功,要 ...

随机推荐

  1. 在Windows2003安装配置Bitvise SSH Server后,不能使用软件内建立的用户登录!

    Google:  I can only log in with an administrator account - attempting to log in with a regular accou ...

  2. Android ScrollView里嵌套RecyclerView时,在RecyclerView上滑动时出现卡顿(冲突)的现象

    最近在项目中遇到一个现象,一个界面有一个RecyclerView(GridView型的),外面套了一层ScrollView,通过ScrollView上下滚动,但是在滑动的时候如果是在RecyclerV ...

  3. 1A课程笔记分享_StudyJams_2017

    1A课程 概述 课程1A主要讲解了Android UI的三种基本控件:TextView.ImageView以及Button.笔记的主体内容主要根据课程内容的讲解顺序来组织,此外我对一些个人比较感兴趣的 ...

  4. Android基础TOP2:单机按钮改变字体颜色

    ---恢复内容开始--- Activity: <TextView android:id="@+id/t1" android:textSize="30dp" ...

  5. SQL基本操作——HAVING

    HAVING:在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用. 我们拥有下面这个 "Orders" 表: O_Id OrderDate Or ...

  6. java编码终极探秘

    首先要明白,java中string字符串都是unicode码保存的,只不过显示的时候会根据一定的规则,比如GBK或者是UTF-8去对照表中查找进行显示. 之所以会乱码就是因为使用错了编码方式. 数据是 ...

  7. 在Excel表格中打字为何会被覆盖掉

    修改证件图片背景:https://www.cnblogs.com/liyanbin/p/9466746.html Insert键是插入和改写(覆盖)的开关如果当前处于改写(覆盖)模式,再按一下Inse ...

  8. PAT_A1107#Social Clusters

    Source: PAT A1107 Social Clusters (30 分) Description: When register on a social network, you are alw ...

  9. SQL With As 用法Sql 四大排名函数(ROW_NUMBER、RANK、DENSE_RANK、NTILE)简介

    Sql 四大排名函数(ROW_NUMBER.RANK.DENSE_RANK.NTILE)简介   排名函数是Sql Server2005新增的功能,下面简单介绍一下他们各自的用法和区别.我们新建一张O ...

  10. 【Linq】标准查询操作符

    A.1 聚合 聚合操作符(见表A-1),所有的结果只有一个值而不是一个序列. Average 和 Sum 针对数值 (任何内置数值类型)序列或使用委托从元素值转换为内置数值类型的元素序列. Min 和 ...