Oracle--JDBC Oracle LONG RAWタイプフィールド挿入ピクチャの読み込み
3468 ワード
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