使用JDBC4.0操作Oracle中BLOB类型的数据方法

在jdbc4.0推出后,它的从多的特性正在受到广泛地关注。下面通过本文给大家介绍jdbc4.0操作oracle中blob类型的数据的方法。

需要的jar包

使用ojdbc6.jar

在/meta-inf/manifest.mf里可以看到specification-version: 4.0

建表

create sequence seq_blobmodel_id start with 1 increment by 1 nocache;
create table blobmodel
(
blobid number(10) primary key not null,
image blob
); 

将文件写入数据库

/**
* 将图片文件存入数据库
* @throws sqlexception
* @throws ioexception
*/
public int writeblob(string path) throws sqlexception, ioexception{
int result = 0;
string sql = "insert into blobmodel(blobid,image) values(seq_blobmodel_id.nextval,?)";
//1.创建blob
blob image = dbhelper.getconnection().createblob();
//2.将流放入blob
outputstream out = image.setbinarystream(1);
//3.读取图片,并写入输出流
fileinputstream fis = new fileinputstream(path);
byte []buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1){
out.write(buf, 0, len);
}
result = dbhelper.executeupdate2(sql, new object[]{image});//自己简单封装了jdbc操作
fis.close();
out.close();
return result;
}

将文件从数据库中读出

/**
* 将数据库中的图片文件读出来
* @throws sqlexception 
* @throws ioexception 
*/
public void readblob() throws sqlexception, ioexception{
string sql = "select image from blobmodel where blobid=?";
dbhelper.getconnection();//
resultset rs = dbhelper.executequery(sql, new object[]{1});
while(rs.next()){
blob image = rs.getblob(1);
inputstream is = image.getbinarystream();
bufferedinputstream bis = new bufferedinputstream(is);
string path = "img/"+new date().gettime()+".jpg";//指定输出的目录为项目下的img文件夹
bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream(path));
byte []buf = new byte[1024];
int len = 0;
while((len=bis.read(buf))!=-1){
bos.write(buf,0,len);
}
bos.close();
bis.close();
}
}

以上所述是www.887551.com给大家介绍的使用jdbc4.0操作oracle中blob类型的数据的方法,希望对大家有所帮助

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐