Oracle中BLOB和CLOB欄位的操作
阿新 • • 發佈:2019-02-01
一、區別和定義
LONG: 可變長的字串資料,最長2G,LONG具有VARCHAR2列的特性,可以儲存長文字一個表中最多一個LONG列
LONG RAW: 可變長二進位制資料,最長2G
CLOB: 字元大物件Clob 用來儲存單位元組的字元資料
NCLOB: 用來儲存多位元組的字元資料
BLOB: 用於儲存二進位制資料
BFILE: 儲存在檔案中的二進位制資料,這個檔案中的資料只能被只讀訪。但該檔案不包含在資料庫內。
bfile欄位實際的檔案儲存在檔案系統中,欄位中儲存的是檔案定位指標.bfile對oracle來說是隻讀的,也不參與事務性控制和資料恢復.
CLOB,NCLOB,BLOB都是內部的LOB(Large Object)型別,最長4G,沒有LONG只能有一列的限制
要儲存圖片、文字檔案、Word檔案各自最好用哪種資料型別?
--BLOB最好,LONG RAW也不錯,但Long是oracle將要廢棄的型別,因此建議用BLOB。
二、操作
1、 get
CLOB
java 程式碼- //獲得資料庫連線
- Connection con = ConnectionFactory.getConnection();
- con.setAutoCommit(false);
- Statement st = con.createStatement();
- //不需要“for update”
- ResultSet rs = st.executeQuery(
- if (rs.next())
- {
- java.sql.Clob clob = rs.getClob("CLOBATTR");
- Reader inStream = clob.getCharacterStream();
- char[] c = newchar[(int) clob.length()];
- inStream.read(c);
- //data是讀出並需要返回的資料,型別是String
- data =
- inStream.close();
- }
- inStream.close();
- con.commit();
- con.close();
BLOB
java 程式碼- //獲得資料庫連線
- Connection con = ConnectionFactory.getConnection();
- con.setAutoCommit(false);
- Statement st = con.createStatement();
- //不需要“for update”
- ResultSet rs = st.executeQuery("select BLOBATTR from TESTBLOB where ID=1");
- if (rs.next())
- {
- java.sql.Blob blob = rs.getBlob("BLOBATTR");
- InputStream inStream = blob.getBinaryStream();
- //data是讀出並需要返回的資料,型別是byte[]
- data = newbyte[input.available()];
- inStream.read(data);
- inStream.close();
- }
- inStream.close();
- con.commit();
- con.close();
2、 put
CLOB
java 程式碼- //獲得資料庫連線
- Connection con = ConnectionFactory.getConnection();
- con.setAutoCommit(false);
- Statement st = con.createStatement();
- //插入一個空物件empty_clob()
- st.executeUpdate("insert into TESTCLOB (ID, NAME, CLOBATTR) values (1, "thename", empty_clob())");
- //鎖定資料行進行更新,注意“for update”語句
- ResultSet rs = st.executeQuery("select CLOBATTR from TESTCLOB where ID=1 for update");
- if (rs.next())
- {
- //得到java.sql.Clob物件後強制轉換為oracle.sql.CLOB
- oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob("CLOBATTR");
- Writer outStream = clob.getCharacterOutputStream();
- //data是傳入的字串,定義:String data
- char[] c = data.toCharArray();
- outStream.write(c, 0, c.length);
- }
- outStream.flush();
- outStream.close();
- con.commit();
- con.close();
- //獲得資料庫連線
- 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();