【转】JDBC学习笔记(6)——获取自动生成的主键值&处理Blob&数据库事务处理
转自:http://www.cnblogs.com/ysw-go/
获取数据库自动生成的主键
我们这里只是为了了解具体的实现步骤:我们在插入数据的时候,经常会需要获取我们插入的这一行数据对应的主键值。
具体的代码实现:

1 /**
2 * 获取数据库自动生成的主键
3 */
4 @Test
5 public void testGetKeyValues(){
6 Connection connection=null;
7 PreparedStatement preparedStatement=null;
8 ResultSet rs=null;
9 try {
10 connection=JDBCTools.getConnection();
11 String sql="insert into customers(name,email,birth)"+
12 " values(?,?,?)";
13 // preparedStatement=connection.prepareStatement(sql);
14 //我们这里使用重载的prepareStatement(sql,flag)方法
15 //来生成prepareStatement对象
16 preparedStatement=connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
17 preparedStatement.setString(1, "ABCDE");
18 preparedStatement.setString(2, "abcd@guigu.com");
19 preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
20 preparedStatement.executeUpdate();
21 //通过getGeneratedKeys方法获取包含了新生成的主键的ResultSet对象
22 //在ResultSet结果集中,只包含一列,列名:GENERATED_KEY,用于存放新生成的主键值
23 rs=preparedStatement.getGeneratedKeys();
24 if(rs.next()){
25 System.out.println(rs.getObject(1));
26 }
27 ResultSetMetaData rsmd=rs.getMetaData();
28 for(int i=0;i<rsmd.getColumnCount();i++){
29 System.out.println(rsmd.getColumnName(i+1));
30 }
31 } catch (Exception e) {
32 e.printStackTrace();
33 }finally{
34 JDBCTools.release(rs,preparedStatement,connection);
35 }
36 }

处理Blob
Blob的基本概念


1).插入Blob类型数据

/**
* 插入Blob类型的数据必须使用PreparedStatement
* 因为Blob类型的数据是无法使用字符串拼写的
*
* 调用setBlob(int index,InputStream,inputStream)
*/

具体代码实现:

1 @Test
2 public void testInsertBlod(){
3 Connection connection=null;
4 PreparedStatement preparedStatement=null;
5 ResultSet rs=null;
6 try {
7 connection=JDBCTools.getConnection();
8 String sql="insert into customers(name,email,birth,picture)"+
9 " values(?,?,?,?)";
10 // preparedStatement=connection.prepareStatement(sql);
11 //我们这里使用重载的prepareStatement(sql,flag)方法
12 //来生成prepareStatement对象
13 preparedStatement=connection.prepareStatement(sql);
14 preparedStatement.setString(1, "ABCDE");
15 preparedStatement.setString(2, "abcd@guigu.com");
16 preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
17 InputStream inputStream=new FileInputStream("blob.png");
18 preparedStatement.setObject(4, inputStream);
19 preparedStatement.executeUpdate();
20
21 } catch (Exception e) {
22 e.printStackTrace();
23 }finally{
24 JDBCTools.release(rs,preparedStatement,connection);
25 }
26 }

2).读取Blob类型数据
/**
* 读取Blob数据:
* 1.使用getBlob方法,读取Blod对象
* 2.调用Blob的getBinaryStream()方法得到输入流,再使用IO操作即可
*/
具体代码实现:

1 @Test
2 public void testReadBlob(){
3 Connection connection = null;
4 PreparedStatement preparedStatement = null;
5 ResultSet resultSet = null;
6 try {
7 connection = JDBCTools.getConnection();
8 String sql = "select id,name,email,birth,picture"+
9 " from customers where id =18";
10 preparedStatement = connection.prepareStatement(sql);
11 resultSet = preparedStatement.executeQuery();
12 if (resultSet.next()) {
13 int id=resultSet.getInt(1);
14 String name=resultSet.getString(2);
15 String email=resultSet.getString(3);
16 System.out.println(id+":"+name+":"+email);
17 Blob pictureBlob=resultSet.getBlob(5);
18 InputStream inputStream=pictureBlob.getBinaryStream();
19 OutputStream out=new FileOutputStream("flo.png");
20 byte[] buffer=new byte[1024];
21 int len =0;
22 while((len=inputStream.read(buffer))!=-1){
23 out.write(buffer,0,len);
24 }
25 out.close();
26 inputStream.close();
27 }
28 } catch (Exception e) {
29 e.printStackTrace();
30 } finally {
31 JDBCTools.release(resultSet, preparedStatement, connection);
32 }
33 }

数据库事务
数据库事务概述

数据库事务的四个属性

JDBC的数据库事务

我们做一个小实验:
先建立一个数据表:

试验中要用到的更新数据的通用方法update():

1 public static void update(Connection connection,String sql,
2 Object ...args){
3 /**
4 * 执行SQL语句,使用PreparedStatement
5 */
6 PreparedStatement preparedStatement=null;
7 try {
8 preparedStatement=connection.prepareStatement(sql);
9 for(int i=0;i<args.length;i++){
10 preparedStatement.setObject(i+1, args[i]);
11 }
12 preparedStatement.executeUpdate();
13 } catch (Exception e) {
14 e.printStackTrace();
15 }finally{
16 JDBCTools.release(null, preparedStatement, null);
17 }

我们要完成的是:Tom->Jerry汇款500元
* 数据库事务
* 关于事务:
* 1.如果多个操作,每个操作使用的是自己的单独的连接,则无法保证事务
* 2.具体步骤:
* 1).开始事务,取消默认自动提交行为
* 2).如果事务的操作都成功,则提交事务:connection.commit();
* 3).回滚事务:若出现异常,则在catch块中回滚事务
我们组织代码就按照上面的步骤来进行.

1 public void testTeansaction() throws Exception{
2 Connection connection=null;
3 try {
4 connection=JDBCTools.getConnection();
5 System.out.println(connection.getAutoCommit());
6 String sql="update users set balance=balance-500 where id=1";
7 //开始事务:取消默认提交
8 connection.setAutoCommit(false);
9 update(connection,sql);
10 int i=10/0;
11 System.out.println(i);
12 sql="update users set balance=balance+500 where id=2";
13 JDBCTools.update(sql);
14 //提交事务
15 connection.commit();
16 } catch (Exception e) {
17 e.printStackTrace();
18 //回滚事务
19 try {
20 connection.rollback();
21 } catch (SQLException e1) {
22 e1.printStackTrace();
23 }
24 }finally{
25 //关闭连接
26 JDBCTools.release(null, null, connection);
27 }
28 }

可以发现,因为我们使用的是同一个connection连接,当异常(除数为0)发生的时候,事务会发生回滚,数据库的数据会恢复到事务开始之前的状态.
【转】JDBC学习笔记(6)——获取自动生成的主键值&处理Blob&数据库事务处理的更多相关文章
- JDBC学习笔记(6)——获取自动生成的主键值&处理Blob&数据库事务处理
获取数据库自动生成的主键 [孤立的技术是没有价值的],我们这里只是为了了解具体的实现步骤:我们在插入数据的时候,经常会需要获取我们插入的这一行数据对应的主键值. 具体的代码实现: /** * 获取数据 ...
- JDBC 获取自动生成的主键
为什么需要获取自动生成的主键 例如:
- Java -- JDBC 获取数据库自动 生成的主键值
public class Demo4 { /* create table test1 ( id int primary key auto_increment, name varchar(20) ); ...
- MYSQL 之 JDBC(十一): JDBC获取插入记录的主键值
取得数据库自动生成的主键值 package com.litian.jdbc; import javax.swing.plaf.nimbus.State; import java.sql.*; /** ...
- (jdbc)取得数据库自动生成的主键方法
一些类,在前面的博客中有,就不重复了 public class Test2 { TestDAO t=new TestDAO(); /*前提是数据表的主键是自动增加的, *取得数据库自动生成的主键 * ...
- javaweb学习总结(三十七)——获得MySQL数据库自动生成的主键
测试脚本如下: 1 create table test1 2 ( 3 id int primary key auto_increment, 4 name varchar(20) 5 ); 测试代码: ...
- Java_jdbc 基础笔记之十五 数据库连接(取得数据库自动生成的主键)
public class testGetKeyValue { /** * 取得数据库自动生成的主键 */ @Test public void testGeneratedKeys() { Connect ...
- 五.获得MYSQL数据库自动生成的主键
测试脚本如下: 1 create table test1 2 ( 3 id int primary key auto_increment, 4 name varchar(20) 5 ); 测试代码: ...
- javaweb(三十七)——获得MySQL数据库自动生成的主键
测试脚本如下: 1 create table test1 2 ( 3 id int primary key auto_increment, 4 name varchar(20) 5 ); 测试代码: ...
随机推荐
- 清空file文件域的方法
我们在实际应用中经常希望能把文件域给清空,比如使用change事件时,因为不清空再次选择同一文件时将不在触发change事件. 但是在IE中,由于安全设置的原因,是不允许更改文件域的值的,也就是不能使 ...
- cocos2dx 魔塔项目总结(一)
<魔塔天城>发布已经有半年的时间了,一直想找时间来总结一下这个项目,但总是一拖再拖.如果再这么拖下去,就永远都不会有时间来写这个总结了,时间总是挤出来的. 魔塔天城使用的cocos2dx ...
- TypeScript设计模式之职责链、状态
看看用TypeScript怎样实现常见的设计模式,顺便复习一下. 学模式最重要的不是记UML,而是知道什么模式可以解决什么样的问题,在做项目时碰到问题可以想到用哪个模式可以解决,UML忘了可以查,思想 ...
- IIS HTTP 错误 500.19 - Internal Server Error HTTP 错误 401.3 - Unauthorized 解决办法
前言:IIS是一个强大的服务器管理器,当遇到 IIS HTTP 错误 500.19 - Internal Server Error HTTP 错误 401.3 - Unauthorized 的解决办 ...
- RabbitMQ-从基础到实战(4)— 消息的交换(下)
0.目录 RabbitMQ-从基础到实战(1)- Hello RabbitMQ RabbitMQ-从基础到实战(2)- 防止消息丢失 RabbitMQ-从基础到实战(3)- 消息的交换(上) 1.简介 ...
- 混合高斯模型(GMM)推导及实现
作者:桂. 时间:2017-03-20 06:20:54 链接:http://www.cnblogs.com/xingshansi/p/6584555.html 声明:欢迎被转载,不过记得注明出处哦 ...
- windows phone 8.1 FlipView 实现照片自动浏览
FlipView 控件也是一个集合控件,不过它和ListView等控件不同,ListView控件是一次显示多个项,而FlipView则是每次只显示一个项.在windows phone上通过默认的左右滑 ...
- KeychainItemWrapper的使用
KeychinaItemWrapper官方Demo下载地址KeychinaItemWrapper. NSString *identifier = @"xxxxxx";//你要使用的 ...
- React Native 之 数据持久化
前言 因为 实战项目系列 涉及到数据持久化,这边就来补充一下. 如本文有错或理解偏差欢迎联系我,会尽快改正更新! 如有什么问题,也可直接通过邮箱 277511806@qq.com 联系我. demo链 ...
- 苹果ATS特性服务器证书配置指南
配置指南: 需要配置符合PFS规范的加密套餐,目前推荐配置: ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!AD ...