1. 程式人生 > >LONG、BLOB、CLOB的區別以及在ORALCE中的插入和查詢操作

LONG、BLOB、CLOB的區別以及在ORALCE中的插入和查詢操作

    插入BLOB 
    //獲得資料庫連線  
    Connection con = ConnectionFactory.getConnection();  
    con.setAutoCommit(false);  
    Statement st = con.createStatement();  
    //插入一個空物件empty_blob()  
    st.executeUpdate("insert into TESTBLOB (ID, NAME, BLOBATTR) values (1, "thename", empty_blob())");  
    //鎖定資料行進行更新,注意“for update”語句  
    ResultSet rs = st.executeQuery("select BLOBATTR from TESTBLOB where ID=1 for update");  
    if (rs.next())  
    {  
        //得到java.sql.Blob物件後強制轉換為oracle.sql.BLOB  
        oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("BLOBATTR");  
        OutputStream outStream = blob.getBinaryOutputStream();  
        //data是傳入的byte陣列,定義:byte[] data  
        outStream.write(data, 0, data.length);  
    }  
    outStream.flush();  
    outStream.close();  
    con.commit();  
    con.close(); 
    Hibernate儲存BLOB物件
 
    public void addMessage(Messages message,String content_str) {
        Session session = this.getSession();
        message.setContent(Hibernate.createBlob(new byte[1]));
        session.save(message);
        session.flush();
        session.refresh(message, LockMode.UPGRADE);
        SerializableBlob sb = (SerializableBlob)message.getContent(); 
        BLOB blob = (BLOB)sb.getWrappedBlob();
        try {
                OutputStream out = blob.getBinaryOutputStream();
                out.write(content_str.getBytes());
                out.close();
                session.save(message);
         } catch (Exception e) {
           e.printStackTrace();
       }
    }