下面以程序實例說明通過JDBC操縱Oracle數據庫LOB類型字段的幾種情況。
先建立如下兩個測試用的數據庫表,Power Designer PD模型如下:
建表SQL語句為:
CREATE TABLE TEST_CLOB ( ID NUMBER(3), CLOBCOL CLOB)
CREATE TABLE TEST_BLOB ( ID NUMBER(3), BLOBCOL BLOB)
一、 CLOB對象的存取
1、往數據庫中插入一個新的CLOB對像
public static void clobInsert(String infile) throws Exception
{
/* 設定不自動提交 */
boolean defaultCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
try {
/* 插入一個空的CLOB對像 */
stmt.executeUpdate("INSERT INTO TEST_CLOB VALUES ('111', EMPTY_CLOB())");
/* 查詢此CLOB對象並鎖定 */
ResultSet rs = stmt.executeQuery("SELECT CLOBCOL FROM TEST_CLOB WHERE ID='111' FOR UPDATE");
while (rs.next()) {
/* 取出此CLOB對像 */
oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob("CLOBCOL");
/* 向CLOB對像中寫入數據 */
BufferedWriter out = new BufferedWriter(clob.getCharacterOutputStream());
BufferedReader in = new BufferedReader(new FileReader(infile));
int c;
while ((c=in.read())!=-1) {
out.write(c);
}
in.close();
out.close();
}
/* 正式提交 */
conn.commit();
} catch (Exception ex) {
/* 出錯回滾 */
conn.rollback();
throw ex;
}
/* 恢復原提交狀態 */
conn.setAutoCommit(defaultCommit);
}
2、修改CLOB對像(是在原CLOB對像基礎上進行覆蓋式的修改)
public static void clobModify(String infile) throws Exception
{
/* 設定不自動提交 */
boolean defaultCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
try {
/* 查詢CLOB對象並鎖定 */
ResultSet rs = stmt.executeQuery("SELECT CLOBCOL FROM TEST_CLOB WHERE ID='111' FOR UPDATE");
while (rs.next()) {
/* 獲取此CLOB對像 */
oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob("CLOBCOL");
/* 進行覆蓋式修改 */
BufferedWriter out = new BufferedWriter(clob.getCharacterOutputStream());
BufferedReader in = new BufferedReader(new FileReader(infile));
int c;
while ((c=in.read())!=-1) {
out.write(c);
}
in.close();
out.close();
}
/* 正式提交 */
conn.commit();
} catch (Exception ex) {
/* 出錯回滾 */
conn.rollback();
throw ex;
}
/* 恢復原提交狀態 */
conn.setAutoCommit(defaultCommit);
}
[1] [2] [3] [4] 下一页