赞
踩
Clob类型为大字段类型默认4000长度,Blob为二进制类型常用存文件数据;这两种大字段类型开发中不会经常遇到,博主整理了这两种大字段与String的转换方法可参考(使用Junit直接测试)其中javax.sql.rowset.serial.SerialClob 和javax.sql.rowset.serial.SerialBlob两个类都是从JDK1.5引入;用到了JDK1.7语法:try...with ,要流实现了Closeable接口就可以使用
1.Blob与String互转
- @Test
- public void testGetBlob() {
- String str ="aaabbbccc";
- Blob blob = null;
- try {
- blob= new javax.sql.rowset.serial.SerialBlob(str.getBytes());
- } catch (SQLException e) {
- e.printStackTrace();
- }
- // blob 转 String
- try(InputStream inputStream = blob.getBinaryStream()){
- byte[] bs = new byte[2048];
- StringBuffer sb = new StringBuffer();
- int len =0;
- while((len=inputStream.read(bs))!=-1) {
- sb.append(new String(bs,0,len));
- }
- System.out.println("blob to String >>"+sb.toString());
- } catch (IOException e) {
- e.printStackTrace();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- }
2.Clob与String互转:
- @Test
- public void testGetClob() {
- //String转clob
- String str ="aaabbbccc";
- Clob clob = null;
- try {
- clob = new javax.sql.rowset.serial.SerialClob(str.toCharArray());
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- // clob 转String
- try(Reader rsReader = clob.getCharacterStream()){
- char [] chs = new char[2048];
- StringBuffer sb = new StringBuffer();
- int i =0;
- while((i=rsReader.read(chs))!=-1) {
- sb.append(chs,0,i);
- }
- System.out.println("clob to string >>"+sb.toString());
- }catch (Exception e) {
- e.printStackTrace();
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。