Blob在java和oracle中的处理方法
一、Blob在java中处理方法。
(一)String转blob。
String string_daily_text = "我修改了日志:20181223,今天在家写代码";
Blob b = new SerialBlob(string_daily_text.getBytes("GBK"));
Daily daily=new Daily("20181223-家里工作日志",b);//Daily类中有属性为Blob类型。
(二)blob转String。
Connection con = dbUtil.getCon();//获取连接
String sql = "select * from daily where daily_id=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, id);
ResultSet rs =pstmt.executeQuery();
if(rs.next()){
Blob b = rs.getBlob("daily_text");
String content = new String(b.getBytes((long)1, (int)b.length()));
System.out.println("日志内容:\n"+content);
}
二、Blob在oracle中的处理方法。
(一)String转blob。
rawtohex(#{daily_text})
update daily set daily_name=#{daily_name},daily_text=rawtohex(#{daily_text}) where daily_id=#{daily_id}
表daily中daily_text字段为blob类型
-- 1、insert
insert into daily(daily_name,daily_text) values ('20181223-家里工作日志',rawtohex('在家写代码'));
-- 2、update
update daily set daily_text=rawtohex('呵呵') where daily_id=12;
(二)blob转String。
1、可以创建一个函数。(Blob_To_Varchar)
--Only for Oracle 注意字段数据类型转换
Create Or Replace Function Blob_To_Varchar (Blob_In In Blob) Return Varchar2
Is
V_Varchar Varchar2(4000);
V_Start Pls_Integer := 1;
V_Buffer Pls_Integer := 4000;
Begin
If Dbms_Lob.Getlength(Blob_In) Is Null Then
Return '';
End If;
For I In 1..Ceil(Dbms_Lob.Getlength(Blob_In) / V_Buffer) Loop
--当转换出来的字符串乱码时,可尝试用注释掉的函数
--V_Varchar := Utl_Raw.Cast_To_Varchar2(Utl_Raw.Convert(Dbms_Lob.Substr(Blob_In, V_Buffer, V_Start),'SIMPLIFIED CHINESE_CHINA.ZHS16GBK', 'AMERICAN_THE NETHERLANDS.UTF8'));
V_Varchar := Utl_Raw.Cast_To_Varchar2(Dbms_Lob.Substr(Blob_In, V_Buffer, V_Start));
V_Start := V_Start + V_Buffer;
End Loop;
Return V_Varchar;
End Blob_To_Varchar;
2、调用函数
select daily_id,daily_name,Blob_To_Varchar(daily_text) from daily;