使用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(); } }
相关推荐
chongxiaocheng 2020-08-16
半纸药笺 2020-06-14
兄dei努力赚钱吧 2020-06-11
northwindx 2020-05-31
huangchunxia 2020-05-28
ELEMENTS爱乐小超 2020-05-28
chognzhihongseu 2020-02-20
zhaojp0 2020-01-24
容数据服务集结号 2020-01-21
jjddrushi 2019-12-27
tlsmile 2019-12-27
yongzhang 2019-12-19
JumpingYeah 2019-12-05
常言道 2019-12-03
Streamoutput 2019-11-08
E哥的aws认证攻略 2019-11-03
牧码人 2019-11-03
阿亮 2019-10-31
MingoJiang 2019-10-28