日期:2014-05-16  浏览次数:20521 次

oracle Blob对象的读写 (插入Blob)

?CREATE SEQUENCE? "ZW"."STUDENT_SEQ"? MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 81 CACHE 20 NOORDER? NOCYCLE ;

?

public class InsertImage extends HttpServlet {??????????? //插入blob,先获取id? (id自增有个触发器给删除了)

?protected void doGet(HttpServletRequest req, HttpServletResponse resp)
???throws ServletException, IOException {
??doPost(req,resp);
?}

?protected void doPost(HttpServletRequest req, HttpServletResponse resp)
???throws ServletException, IOException {
??
??//?String fileName="D:\\My Documents\\My Pictures\\colorjb33.bmp";
??int id=this.getId();??????????????????????????????? //同一个id
??String name=req.getParameter("name");
??String fileName=req.getParameter("fileName");
???Blob b=null;
???int i=0;
???OracleConnection oc=new OracleConnection();
???Connection conn=oc.getConnection();
???try {
????String sql="insert into student(id,name,image) values(?,?,empty_blob())";
????
?????PreparedStatement ps=conn.prepareStatement(sql);
?????ps.setInt(1, id);
?????ps.setString(2, name);
???? i=?ps.executeUpdate();
???? ps.close();
???? System.out.println("insert empty_blob");
???String sl="select image from student where id=? for update";
???PreparedStatement ps2=conn.prepareStatement(sl);
???ps2.setInt(1, id);
???ResultSet rs2=ps2.executeQuery();
???
???byte[] buf=new byte[1024];
???if(rs2.next()){
???? b=rs2.getBlob("image");
???? System.out.println(b);
???? BufferedOutputStream bos=new BufferedOutputStream(b.setBinaryStream(0));
???? BufferedInputStream bis=new BufferedInputStream(new FileInputStream(fileName));
???? while(bis.read(buf)!=-1){
????? bos.write(buf);
???? }
???? bos.close();
???? bis.close();
???}
???rs2.close();
???ps2.close();
???conn.close();
???} catch (Exception e) {
????e.printStackTrace();
???}
??System.out.println("success.............");
?}
?private int getId(){
??int id=0;
??OracleConnection oc=new OracleConnection();
??Connection conn=oc.getConnection();
??String sql="select student_seq.nextval from dual";
??try {
???PreparedStatement ps=conn.prepareStatement(sql);
???
??ResultSet rs=ps.executeQuery();
??if(rs.next()){
???id=rs.getInt(1);
??}
?? ps.close();
?? conn.close();
??} catch (SQLException e) {
???e.printStackTrace();
??}
??return id;
?}
}