java long raw_Oracle--JDBC读取Oracle LONG RAW类型字段插入图片

今天在项目中要向Oracle的LONG RAW形字段插入图片,以配合C/S的设计结构

项目中用Hibernate ORM,找了N久没有找到具体操作方法,终于花了2个多小时找到一个JDBC操作的例子,代码改造后为

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class JdbcImgDAO {

//数据库连接方法

public static Connection getConnection(){

String url="jdbc:oracle:thin:@192.168.0.100:1521:testdb";

Connection conn = null;

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

conn=DriverManager.getConnection(url,"user","pwd");

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

return conn;

}

//插入图片到案例库,id为主键,s为上传图片(路径+图片名)

public static void updateImg(String id, String s){

Connection conn = getConnection();

String sql="update table t set t.img=? where id=?";

File filename=new File(s);

//将文件的长度读出,并转换成Long型

long l1=filename.length();

int l2=(int)l1;

try {

//以流的格式赋值

FileInputStream fis=new FileInputStream(filename);

PreparedStatement ps =conn.prepareStatement(sql);

ps.setBinaryStream(1,fis,l2);

//ps.setBinaryStream(1,fis,fis.available());

ps.setString(2,id);

ps.executeUpdate();

ps.close();

fis.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

try {

conn.rollback();

} catch (SQLException e1) {

e1.printStackTrace();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

显示图片页

img.jsp

String id = request.getParameter("id");

String URL="jdbc:oracle:thin:@192.168.0.100:1521:testdb";

String user="user";

String password="pwd";

Connection con = DriverManager.getConnection(URL,user,password);

InputStream in = null;

ResultSet rs = null;

OutputStream out = response.getOutputStream();

try{

Statement stmt = con.createStatement();

String sql = "select t.img from table t where id="+id;

rs = stmt.executeQuery(sql);

while(rs.next()) {

in = rs.getBinaryStream("img");

int len = 0;

byte[] byte = new byte[1024];

//response.setContentType("image/jpeg");

while ((len = in.read(byte)) != -1) {

out.write(byte,0,len);

}

out.close();

in.close();

}

}catch(Exception e){

e.printStackTrace();

}finally{

rs.close();

con.close();

}

%>

显示信息页面

img.jsp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值