使用jdbc连接oracle进行crud,java的UUID类型字段,如何通过jdbc进行数据库的CRUD

关键字:UUID byte[] jdbc mysql java

1、UUID/GUID概念

UUID含义是通用唯一识别码 (Universally Unique Identifier),这 是一个软件建构的标准,也是被开源软件基金会 (Open Software Foundation, OSF) 的组织应用在分布式计算环境 (Distributed Computing Environment, DCE) 领域的一部份。

A UUID is a 16-byte (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 digits and four hyphens). For example:

550e8400-e29b-41d4-a716-446655440000

There are 340,282,366,920,938,463,463,374,607,431,768,211,456 possible UUIDs (16 to the 32nd power), or about 3 × 1038.

详细介绍请参考http://en.wikipedia.org/wiki/Universally_Unique_Identifier。

2、java中的类java.Util.UUID

jdk1.5增加了类java.Util.UUID,用于方便生成UUID。

UUID uuid=UUID.randomUUID();

String uuidStr=uuid.toString();//生成的如:9b17a4f1-cae4-42ce-9cba-b899dcac8517

UUID类中还有个方法也常用:UUID.fromString(name)

Creates a UUID from the string standard representation as described in the toString method.

3、数据库中UUID的存储类型

常用的存储方式两种,以mySql数据库为例(关于oracle数据库,测试后再贴)

字符串方式:char(36)

字节方式(二进制):binaray(36)

创建表结构:

create table guid(id binary(36),uuid char(36));

4、jdbc如何操作

@Test

public void guid(){

UUID uuid=UUID.randomUUID();

String sqlSelect="select id,uuid from guid";

String sqlInsert="insert into guid(id,uuid) values(?,?)";

String sqlDelete="delete from guid where id=?";

try{

JDBConnection conn=new JDBConnection();

try{

//insert

PreparedStatement ps=conn.getConect().prepareStatement(sqlInsert);

//id列,参数为byte[]或者String都可以

ps.setObject(1, uuid.toString().getBytes());

//uuid列

ps.setString(2, uuid.toString());

ps.executeUpdate();

//select

ResultSet result=conn.executeQuery(sqlSelect);

while(result.next()){

Object id=result.getObject(1);//获取的byte[]

Object uid=result.getObject(2);

String ids=result.getString(1);

Assert.assertEquals(uid, uuid.toString());

Assert.assertEquals(ids,uuid.toString());

//byte[]转换为UUID字符串

Assert.assertEquals(new String((byte[])id),uuid.toString());

Assert.assertEquals(UUID.fromString(ids).toString(),uuid.toString());

}

//delete

ps=conn.getConect().prepareStatement(sqlDelete);

//id列,参数为byte[]或者String都可以

ps.setObject(1, uuid.toString().getBytes());

ps.executeUpdate();

}catch(Exception ex){

ex.printStackTrace();

}finally{

conn.close();

}

}catch(Exception e){

e.printStackTrace();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值