每日一得

          不求多得,只求一得 about java,hibernate,spring,design,database,Ror,ruby,快速開(kāi)發(fā)
          最近關(guān)心的內(nèi)容:SSH,seam,flex,敏捷,TDD
          本站的官方站點(diǎn)是:顛覆軟件

            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            220 隨筆 :: 9 文章 :: 421 評(píng)論 :: 0 Trackbacks
          key words : blob , oracle ,插入圖片

          come from  here

          顯示blob

          try {
          Class.forName(
          "sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
          Connection con
          =DriverManager.getConnection("jdbc:odbc:Multimedia","samp","samp");
          Statement stmt
          =con.createStatement();
          ResultSet rs
          =stmt.executeQuery("select frame from MULTIMEDIA_TAB where clip_id=1");
          if(rs.next()){
          try {
          InputStream dis
          =rs.getBinaryStream(1);
          byte[] x = new byte [10*1024]; //creare byte array to hold the blob data
          int lengthRead = 0// Number of bytes read
          String fileToWriteBlob = "./default-app/MyProgs/ImageRetrieval/ganpati.jpg";
          FileOutputStream outputStream 
          = new FileOutputStream(fileToWriteBlob);
          while( (lengthRead =dis.read(x)) != -1){
          outputStream.write(x);
          }

          dis.close();
          outputStream.close();
          }

          catch(Exception e) {
          System.out.println (
          "Error is : " + e);
          }

          }

          }

          catch(Exception ex) {
          System.out.println(
          "Error " + ex);
          }
           


          If you are inserting a row:

          1.Insert the row with all values, but insert an empty blob into the blob column:
          "INSERT INTO yourtable (id,blob_value) VALUES (?,empty_blob())"

          2. Select the empty blob you created:
          "SELECT blob_value FROM yourtable WHERE id=?"
          oracle.sql.BLOB blob = rs.getBLOB("blob_value");
          (some code is of course missing, but this should give you the idea)
          3. Write the bytes into the blob:

          try {
          OutputStream outstream = blob.getBinaryOutputStream();
          outstream.write(blobValue);
          outstream.flush();
          outstream.close();
          } catch (IOException e) {
          // handle exception
          }
          Where blobValue is the byte array containing the image data.

          4. Update the row:
          "UPDATE yourtable SET blob_value=? WHERE id=?"
          pstmt.setBLOB(1, blob);
          pstmt.setInt(2, id);
          (NOTE: the setBLOB is an Oracle specific method, you can probably also use the setBlob method).
          Again, some essential code concerning the prepared statements is missing, but this should give you an idea...

          That's that. If you just need to update the row, you just go through steps 2-4 above.


          Here is an example:

          import java.sql.*;
          import java.io.*;

          public class imgtest {

          private PreparedStatement ps = null;
          private Connection conn = null;

          public void initialise() {
          String URL 
          = "jdbc:oracle:thin:@localhost:1521:SID";
          String userid 
          = "user";
          String passwd 
          = "pass";
          // register the JDBC driver
          try {
          DriverManager.registerDriver(
          new
          oracle.jdbc.driver.OracleDriver());
          // get a connection
          Connection conn = DriverManager.getConnection(URL, userid, passwd);
          this.conn = conn;
          // create a prepared statement
          ps = conn.prepareStatement("INSERT INTO images (NAME,IMAGE) VALUES (?,?)");
          }

          catch (Exception e) {
          System.out.println(
          "Error: " + e);
          System.exit(
          1);
          }

          }


          public imgtest() {
          initialise();
          File fImage 
          = null;
          FileInputStream isImage 
          = null;

          try {
          fImage 
          = new File( "fileo.gif" );
          isImage 
          = new FileInputStream( fImage );
          }

          catch (FileNotFoundException fnf) {
          System.out.println(
          "File not found: " + fnf);
          System.exit(
          1);
          }

          try {
          ps.setString(
          1,"Open File");
          ps.setBinaryStream(
          2,isImage,(int)(fImage.length()));
          ps.executeUpdate();
          ps.close();
          conn.close();
          }

          catch (Exception e) {
          System.out.println(
          "Error: " + e);
          System.exit(
          1);
          }

          }


          public static void main(String[] args) {
          new imgtest();
          }

          }
           


          My table looks like this:
          // ---->%----
          CREATE TABLE images
          (NAME VARCHAR2(16) primary key not null,
          IMAGE BLOB(64k));
          commit;
          quit;
          // ---->%----


          update(2007-5-13)
          /**
           * Oracle中的Blob類(lèi)型字段操作
           * User: Alex
           * Date: 2007-5-9
           * Time: 16:42:43
           
          */

          public class BlobUtil {

              
          /**
               * 獲得blob內(nèi)容
               *
               * 
          @param documentId : 文檔編號(hào)
               * 
          @param response   : HttpServletResponse
               
          */

              
          public static void downloadDocument(String documentId, HttpServletResponse response) {
                  
          if (null == documentId) throw new JyhdException("文檔編號(hào)為空,請(qǐng)檢查");

                  DbDao db 
          = null;
                  ResultSet rs 
          = null;
                  BLOB blob 
          = null;
                  OutputStream out 
          = null;
                  
          try {
                      String sql 
          = "select id,file_blob from tbl_blob_document where id = " + documentId;
                      db 
          = new DbDaoImpl();
                      rs 
          = db.query(sql);

                      
          if (rs.next()) {
                          blob 
          = (BLOB) rs.getBlob("file_blob");
                          InputStream in 
          = blob.getBinaryStream();
                          out 
          = response.getOutputStream();
                          
          int size = blob.getBufferSize();
                          
          byte[] buffer = new byte[size]; // 建立緩沖區(qū)
                          int len;
                          
          while ((len = in.read(buffer)) != -1)
                              out.write(buffer, 
          0, len);
                      }

                  }

                  
          catch (Exception e) {
                      e.printStackTrace();
                      
          throw new JyhdException("===>>>table非法");
                  }

                  
          finally {
                      
          try {
                          
          if (null != out) {
                              out.close();
                          }

                          
          if (null != db) {
                              db.close();
                          }

                      }
           catch (Exception ee) {
                          ee.printStackTrace();
                      }

                  }


              }


              
          /**
               * 插入blob內(nèi)容
               * updated: 支持update,動(dòng)態(tài)判斷documentId是否已經(jīng)存在,若已經(jīng)存在則修改
               *
               * 
          @param inputStream : 讀取輸入流
               * 
          @param documentId  :  請(qǐng)從WellsoonUtil.getSequence("TBL_BLOB_DOCUMENT_SEQ") 獲取
               
          */

              
          public static void uploadDocument(InputStream inputStream, String documentId) {
                  DbDao db 
          = null;
                  ResultSet rs 
          = null;
                  Connection conn 
          = null;
                  String sql 
          = null;
                  
          try {
                      db 
          = new DbDaoImpl();
                      conn 
          = db.getConnection();
                      conn.setAutoCommit(
          false);
                      Statement stmt 
          = conn.createStatement();

                      
          //如果已經(jīng)存在則更新
                      String hasOldRecord = "select id from tbl_blob_document where id =" + documentId;
                      
          if (!DbUtil.hasRecord(hasOldRecord)) {
                          sql 
          = "insert into tbl_blob_document( id,file_blob) values(" + documentId + ",EMPTY_BLOB())";
                          
          int count = stmt.executeUpdate(sql);
                      }

                      
          //select for update
                      sql = "select id,file_blob from tbl_blob_document where id = " + documentId + " for update";
                      rs 
          = stmt.executeQuery(sql);

                      
          if (rs.next()) {
                          BLOB blob 
          = ((OracleResultSet) rs).getBLOB("file_blob");  // 得到BLOB對(duì)象
                          OutputStream out = blob.getBinaryOutputStream();  // 建立輸出流
                          int size = blob.getBufferSize();
                          
          byte[] buffer = new byte[size];  // 建立緩沖區(qū)
                          int len;
                          
          while ((len = inputStream.read(buffer)) != -1)
                              out.write(buffer, 
          0, len);
                          inputStream.close();
                          out.close();


                      }

                      conn.commit();

                  }

                  
          catch (Exception e) {
                      e.printStackTrace();
                      
          throw new JyhdException("===>>>table非法");
                  }

                  
          finally {
                      
          try {
                          db.close();
                      }
           catch (Exception ee) {
                          ee.printStackTrace();
                      }

                  }

              }


              
          /**
               * 填充Blob
               
          */

              
          private static void fillBlob(oracle.sql.BLOB blob, byte[] btaData) throws Exception {
                  
          int len = btaData.length;
                  
          long num = 0;
                  
          byte[] btBlockData;
                  
          for (int i = 0; i < len; i += num) {
                      
          if (i == 0)
                          btBlockData 
          = btaData;
                      
          else {
                          btBlockData 
          = new byte[len - i];
                          System.arraycopy(btaData, i, btBlockData, 
          0, len - i);
                      }

                      num 
          = blob.putBytes(i + 1, btBlockData);
                  }

              }


              
          /**
               * dump Blob
               *
               * 
          @param blob
               * 
          @return
               * 
          @throws Exception
               
          */

              
          private static byte[] dumpBlob(oracle.sql.BLOB blob) throws Exception {
                  
          long len = blob.length();
                  
          byte[] byte0 = new byte[(int) len];
                  
          byte[] byte1 = new byte[32512];
                  
          int num = 0;
                  
          for (int i = 0; i < len; i += num) {
                      num 
          = blob.getBytes(i + 1, (int) len - i, byte1);
                      System.arraycopy(byte1, 
          0, byte0, i, num);
                  }

                  byte1 
          = null;
                  
          return byte0;
              }



              
          public static void main(String[] args) throws Exception {
                  
          //文件上傳
                  File file = new File("Y:\\我的照片\\Palm\\Photo_121306_013.jpg");
                  InputStream in 
          = new FileInputStream(file);
                  String sequence 
          = SequenceUtil.getSequence("TBL_BLOB_DOCUMENT_SEQ");
                  uploadDocument(in, sequence);

              }


          }


          posted on 2007-03-28 16:55 Alex 閱讀(4592) 評(píng)論(0)  編輯  收藏 所屬分類(lèi): javadataBase
          主站蜘蛛池模板: 青川县| 东阳市| 昌图县| 敦化市| 夏邑县| 和田市| 莎车县| 阜新| 利川市| 南部县| 周宁县| 同江市| 姚安县| 淮北市| 鸡泽县| 凌云县| 锡林郭勒盟| 尉氏县| 班戈县| 伽师县| 昌邑市| 宣汉县| 连云港市| 赤水市| 西畴县| 壶关县| 池州市| 微山县| 府谷县| 久治县| 车险| 渝中区| 宾川县| 灵山县| 信宜市| 阳东县| 绵阳市| 五台县| 扎囊县| 湛江市| 肇东市|