设有表:
create table blobimg(idintprimarykey,contentsblob);
一、BLOB入库的专用访问:
1)最常见于Oracle的JDBC示例中
一般是先通过select...forupdate锁定blob列,然后写入blob值,然后提交。要用到特定的OracleBLOB类。
Class.forName("oracle.jdbc.driver.OracleDriver");
Connectioncon=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:testdb","test","test");
//处理事务
con.setAutoCommit(false);
Statementst=con.createStatement();
//插入一个空对象
st.executeUpdate("insertintoBLOBIMGvalues(1,empty_blob())");
//用forupdate方式锁定数据行
ResultSetrs=st.executeQuery(
"selectcontentsfromBLOBIMGwhereid=1forupdate");
if(rs.next()){
//使用oracle.sql.BLOB类,没办法了,变成专用的了
oracle.sql.BLOBblob=(oracle.sql.BLOB)rs.getBlob(1).;
//到数据库的输出流
OutputStreamoutStream=blob.getBinaryOutputStream();
//这里用一个文件模拟输入流
Filefile=newFile("d:\\proxy.txt");
InputStreamfin=newFileInputStream(file);
//将输入流写到输出流
byte[]b=newbyte[blob.getBufferSize()];
intlen=0;
while((len=fin.read(b))!=-1){
outStream.write(b,0,len);
}
//依次关闭
fin.close();
outStream.flush();
outStream.close();
}
con.commit();
con.close();
2)再厉害一点的,是通过调用DBMS_LOB包中的一些函数来处理,效率好像也不错.
不过,要使用到存储过程,用到专用类OracleCallableStatement。
例:
importjava.sql.*;
importjava.io.*;
importoracle.jdbc.driver.*;
importoracle.sql.*;
classTestBlobWriteByDBMS_LOB{
publicstaticvoidmain(Stringargs[])throwsSQLException,
FileNotFoundException,IOException
{
DriverManager.registerDriver(neworacle.jdbc.driver.OracleDriver());
Connectionconn=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ora92","scott","tiger");
conn.setAutoCommit(false);
Statementstmt=conn.createStatement();
stmt.execute("deletefromdemo");
System.out.println("deletedfromdemo");
stmt.execute("insertintodemo(id,theBlob)values(s_enr.nextval,empty_blob())");
conn.commit();
System.out.println("committed");
ResultSetrset=stmt.executeQuery("SELECTtheBlobFROMdemowhereid=s_enr.currvalFORUPDATE");
System.out.println("ExecutedQuery");
if(rset.next())
{
System.out.println("Fetchedrow");
BLOBl_mapBLOB=((OracleResultSet)rset).getBLOB(1);
FilebinaryFile=newFile("e:\\free\\jo.jpg");
FileInputStreaminstream=newFileInputStream(binaryFile);
intchunk=32000;
System.out.println("Chunk="+chunk);
byte[]l_buffer=newbyte[chunk];
intl_nread=0;
OracleCallableStatementcstmt=
(OracleCallableStatement)conn.prepareCall("begindbms_lob.writeappend(:1,:2,:3);end;");
cstmt.registerOutParameter(1,OracleTypes.BLOB);
while((l_nread=instream.read(l_buffer))!=-1)
{
cstmt.setBLOB(1,l_mapBLOB);
cstmt.setInt(2,l_nread);
cstmt.setBytes(3,l_buffer);
cstmt.executeUpdate();
l_mapBLOB=cstmt.getBLOB(1);
}
instream.close();
conn.commit();
rset.close();
stmt.close();
conn.close();
}
}
}
二、BLOB值读取的通用处理:
这个jdbc标准接口可以直接调用,因此比较简单,如下所示:
Connectioncon=ConnectionFactory.getConnection();
con.setAutoCommit(false);
Statementst=con.createStatement();
ResultSetrs=st.executeQuery("selectcontentsfromBLOBIMGwhereid=1");
if(rs.next()){
java.sql.Blobblob=rs.getBlob(1);
InputStreamins=blob.getBinaryStream();
//输出到文件
Filefile=newFile("d:\\output.txt");
OutputStreamfout=newFileOutputStream(file);
//下面将BLOB数据写入文件
byte[]b=newbyte[1024];
intlen=0;
while((len=ins.read(b))!=-1){
fout.write(b,0,len);
}
//依次关闭
fout.close();
ins.close();
}
con.commit();
con.close();
三、BLOB值写入的通用处理:
这时要借助于PreparedStatement的动态绑定功能,借用其setObject()方法插入字节流到BLOB字段。
publicvoidinsertFile(Filef)throwsException{
FileInputStreamfis=newFileInputStream(f,Connectionconn);
byte[]buffer=newbyte[1024];
data=null;
intsept=0;intlen=0;
while((sept=fis.read(buffer))!=-1){
if(data==null){
len=sept;
data=buffer;
}else{
byte[]temp;
inttempLength;
tempLength=len+sept;
temp=newbyte[tempLength];
System.arraycopy(data,0,temp,0,len);
System.arraycopy(buffer,0,temp,len,sept);
data=temp;
len=tempLength;
}
if(len!=data.length()){
bytetemp=newbyte[len];
System.arraycopy(data,0,temp,0,len);
data=temp;
}
}
Stringsql="insertintofileData(filename,blobData)value(?,?)";
PreparedStatementps=conn.prepareStatement(sql);
ps.setString(1,f.getName());
ps.setObject(2,data);
ps.executeUpdate();
}
四.CLOB读取的通用处理
publicstaticStringgetClobString(ResultSetrs,intcol){
try{
Clobc=resultSet.getClob(2);
Readerreader=c.getCharacterStream():
if(reader==null){
returnnull;
}
StringBuffersb=newStringBuffer();
char[]charbuf=newchar[4096];
for(inti=reader.read(charbuf);i>0;i=reader.read(charbuf)){
sb.append(charbuf,0,i);
}
returnsb.toString();
}catch(Exceptione){
return"";
}
}
当然还可以直接编写BLOB存取的存储过程供JDBC调用,那也非常方便。不过可能要用到外部LOB类型。