码迷,mamicode.com
首页 > 数据库 > 详细

JDBC学习笔记(6)——获取自动生成的主键值&处理Blob&数据库事务处理

时间:2016-05-06 21:51:22      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:

获取数据库自动生成的主键

【孤立的技术是没有价值的】,我们这里只是为了了解具体的实现步骤:我们在插入数据的时候,经常会需要获取我们插入的这一行数据对应的主键值。

具体的代码实现:

 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&数据库事务处理

标签:

原文地址:http://www.cnblogs.com/ysw-go/p/5467025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!