2008年8月11日星期一

String转CLOB

用下面的方法可以将JAVA的STRING 转化成CLOB类型,不过好像仅限于ORACLE,其他的数据库上我没有试过。
private CLOB getCLOB( String clobData,Connection conn )
throws Exception {
CLOB tempClob = null;
try {
// create a new temporary CLOB

tempClob = CLOB.createTemporary(getNativeConnection(conn) , false,
CLOB.DURATION_SESSION );
// Open the temporary CLOB in readwrite mode to enable writing
tempClob.open( CLOB.MODE_READWRITE );

// Get the output stream to write
Writer tempClobWriter = tempClob.getCharacterOutputStream( );
// Write the data into the temporary CLOB
tempClobWriter.write( clobData );
// Flush and close the stream
tempClobWriter.flush( );
tempClobWriter.close( );
// Close the temporary CLOB
tempClob.close( );
} catch ( Exception exp ) {
// Free CLOB object
throw exp;
//do something
}
return tempClob;
}

如果使用连接池来获得数据库连接,有可能需要将数据库连接进行一下转化,使用以下代码:
private static Connection getNativeConnection(Connection con) throws SQLException {
if (con instanceof DelegatingConnection) {
Connection nativeCon = ((DelegatingConnection) con).getInnermostDelegate();
// For some reason, the innermost delegate can be null: not for a
// Statement''''s Connection but for the Connection handle returned by the pool.
// We''''ll fall back to the MetaData''''s Connection in this case, which is
// a native unwrapped Connection with Commons DBCP 1.1.
return (nativeCon != null ? nativeCon : con.getMetaData().getConnection());
}
return con;
}

没有评论: