使用JDBC4.0处理Oracle中BLOB类型的数据

发表于:2016-8-25 10:13

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:excalimax    来源:51Testing软件测试网采编

  需要的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
);
  将文件写入数据库
1 /**
2      * 将图片文件存入数据库
3      * @throws SQLException
4      * @throws IOException
5      */
6     public int writeBlob(String path) throws SQLException, IOException{
7         int result = 0;
8         String sql = "insert into blobmodel(blobid,image) values(seq_blobmodel_id.nextval,?)";
9         //1.创建Blob
10         Blob image = DBHelper.getConnection().createBlob();
11         //2.将流放入blob
12         OutputStream out = image.setBinaryStream(1);
13         //3.读取图片,并写入输出流
14         FileInputStream fis = new FileInputStream(path);
15         byte []buf = new byte[1024];
16         int len = 0;
17         while((len=fis.read(buf))!=-1){
18             out.write(buf, 0, len);
19         }
20         result = DBHelper.executeUpdate2(sql, new Object[]{image});//自己简单封装了jdbc操作
21
22         fis.close();
23         out.close();
24         return result;
25     }
  将文件从数据库中读出
/**
* 将数据库中的图片文件读出来
* @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();
}
}
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号