日期:2014-05-18 浏览次数:21002 次
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import jdbc.util.CloseResourse; import jdbc.util.ConnectionFactory; /** * create table images(id number(9) primary key,name varchar2(30) not null,image blob) * @author Administrator * */ public class ImageLibraryServer { public void addImage(long id,String imagename,String path){ Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try{ con = ConnectionFactory.getConnection(); con.setAutoCommit(false); String sql = "insert into images(id,name,image) values(?,?,empty_blob())"; ps = con.prepareStatement(sql); ps.setLong(1, id); ps.setString(2, imagename); ps.executeUpdate(); ps.close(); sql = "select image from images where id=? for update"; ps = con.prepareStatement(sql); ps.setLong(1, id); rs = ps.executeQuery(); while(rs.next()){ Blob image = (Blob)rs.getBlob("image");//找到要写入的位置 [u]OutputStream out = image.setBinaryStream(0);//[/u]得到输入流,并指定开始读入的位置 BufferedOutputStream bos = new BufferedOutputStream(out); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path)); int c ; while((c=bis.read())!=-1){ bos.write(c); } bis.close(); bos.close(); } con.commit(); }catch(Exception e){ e.printStackTrace(); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } }finally{ CloseResourse.close(rs, ps, con); } } }
Connection con = MyConnection.getORACLEConnection();
try ...{
java.sql.PreparedStatement pstm = con.prepareStatement(
"select * from testBinary where id='a1'");
ResultSet rs = pstm.executeQuery();
rs.next();
oracle.sql.BLOB blob = (BLOB) rs.getBlob(2);
InputStream is = blob.getBinaryStream();
FileOutputStream fi = new FileOutputStream("f:\aaaa.mp3");
byte[] buff = new byte[1024];
int len = is.read(buff);
while (len != -1) ...{
fi.write(buff);
len = is.read(buff);
}
fi.close();
} catch (SQLException ex) ...{
} catch (FileNotFoundException ex) ...{
ex.printStackTrace();
} catch (IOException ex) ...{
ex.pri