使用JDBC4.0操作Oracle中BLOB类型的数据方法
在JDBC4.0推出后,它的从多的特性正在受到广泛地关注。下面通过本文给大家介绍JDBC4.0操作Oracle中BLOB类型的数据的方法。
需要的jar包
使用ojdbc6.jar
在/META-INF/MANIFEST.MF里可以看到Specification-Version:4.0
建表
createsequenceseq_blobmodel_idstartwith1incrementby1nocache;
createtableblobmodel
(
blobidnumber(10)primarykeynotnull,
imageblob
);
将文件写入数据库
/**
*将图片文件存入数据库
*@throwsSQLException
*@throwsIOException
*/
publicintwriteBlob(Stringpath)throwsSQLException,IOException{
intresult=0;
Stringsql="insertintoblobmodel(blobid,image)values(seq_blobmodel_id.nextval,?)";
//1.创建Blob
Blobimage=DBHelper.getConnection().createBlob();
//2.将流放入blob
OutputStreamout=image.setBinaryStream(1);
//3.读取图片,并写入输出流
FileInputStreamfis=newFileInputStream(path);
byte[]buf=newbyte[1024];
intlen=0;
while((len=fis.read(buf))!=-1){
out.write(buf,0,len);
}
result=DBHelper.executeUpdate2(sql,newObject[]{image});//自己简单封装了jdbc操作
fis.close();
out.close();
returnresult;
}
将文件从数据库中读出
/**
*将数据库中的图片文件读出来
*@throwsSQLException
*@throwsIOException
*/
publicvoidreadBlob()throwsSQLException,IOException{
Stringsql="selectimagefromblobmodelwhereblobid=?";
DBHelper.getConnection();//
ResultSetrs=DBHelper.executeQuery(sql,newObject[]{1});
while(rs.next()){
Blobimage=rs.getBlob(1);
InputStreamis=image.getBinaryStream();
BufferedInputStreambis=newBufferedInputStream(is);
Stringpath="img/"+newDate().getTime()+".jpg";//指定输出的目录为项目下的img文件夹
BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(path));
byte[]buf=newbyte[1024];
intlen=0;
while((len=bis.read(buf))!=-1){
bos.write(buf,0,len);
}
bos.close();
bis.close();
}
}
以上所述是小编给大家介绍的使用JDBC4.0操作Oracle中BLOB类型的数据的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!