---
title: "JDBC读取Oracle LONG RAW类型字段"
author: "独家冠名"
date: "2008-11-25T22:38:53Z"
tags: ["Hibernate", "JDBC", "Java", "Oracle", "SQL"]
categories: ["数据库"]
slug: "jdbc-oracle-long-raw"
draft: false
lastmod: "2010-08-27T19:25:36Z"
id: 278769
url: "https://singlewolf.iteye.com/blog/278769"
---

今天在项目中要向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 &lt;%@ page contentType="text ml; charset=gbk"%&gt; &lt;%@ page import="java.io.\*"%&gt; &lt;%@ page import="java.sql.\*, javax.sql.\*"%&gt; &lt;%@ page import="java.util.\*"%&gt; &lt;% 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(); } %&gt; 显示信息页面 ![](img.jsp)