【转】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 ); 测试代码: ...
随机推荐
- Azure Messaging-ServiceBus Messaging消息队列技术系列3-消息顺序保证
上一篇:Window Azure ServiceBus Messaging消息队列技术系列2-编程SDK入门 http://www.cnblogs.com/tianqing/p/5944573.ht ...
- input解决浏览器记住密码问题
<input type="password" name="" id="">可以这样写 <input type=" ...
- 1036: [ZJOI2008]树的统计Count
1036: [ZJOI2008]树的统计Count Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 7496 Solved: 3078[Submit] ...
- CoreAnimation 寄宿图
#CoreAnimation 寄宿图 寄宿图:图层中所包含的图 by:旭宝爱吃鱼 针对于寄宿图我在这里只讨论contents属性以及Custom Drawing. contents content:内 ...
- 用Jquery做一个时间日期选择器
今天我们就用Jquery做一个时间日期选择器,当打开网页时,文本框里面显示的是当前的日期,点击文本框可以出现年.月.日的下拉菜单,并且可以选择,会根据年份的选择判断是否是闰年,从而改变二月的天数,闰年 ...
- python实现TCP/UDP通信
一.说明 对于TCP/udp的说明已经很多了,我在这里只是简单的说明一下 二.套接字scoket 套接字是一种具有之前所说的"通信端点"概念的计算网络数据结构.相当于电话插口,没它 ...
- c#关于时间TimeHelper类的总结
using System; namespace DotNet.Utilities{ /// <summary> /// 时间类 /// 1.SecondToMinute( ...
- iOS开发之instancetype
instancetype和id使用方法类似,但他们还有不同点: (1)instancetype在类型表示上,跟id一样,可以表示任何对象类型 (2)instancetype只能用在返回值类型上,不能像 ...
- 组件之间使用Prop传递数据
<div id="example"> <father></father> </div> <script src="h ...
- The superclass “javax.servlet.http.HttpServlet" was not found on the Java Build Path错误
1.异常信息 创建maven web项目时,出现 The superclass "javax.servlet.http.HttpServlet" was not found on ...