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 

<%@ page contentType="text ml; charset=gbk"%> 
<%@ page import="java.io.*"%> 
<%@ page import="java.sql.*, javax.sql.*"%> 
<%@ page import="java.util.*"%> 
<% 
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 src="img.jsp"> 

  开发者博客www.developsearch.com

猜你喜欢

转载自keepwork.iteye.com/blog/1945962
今日推荐