设为首页 收藏本站
查看: 819|回复: 0

[经验分享] Handling CLOBs

[复制链接]

尚未签到

发表于 2016-7-29 07:44:15 | 显示全部楼层 |阅读模式
Handling CLOBs - Made easy with Oracle JDBC 10g


Date: 17-Mar-2004


This document will help you understand: 

· How to easily handle the CLOB data
at  the  JDBC        layer using enhanced APIs available with Oracle JDBC
10g


· How to run the sample Java application demonstrating the
easy   handling        of CLOB data in the JDBC code.


Table of Contents
  Introduction


Prerequisites


Software Requirements


How to Handle CLOBs Easily in
JDBC?


Running the Sample Java Application


Useful References



Introduction



JDBC (Java Database Connectivity) is a standard Java
interface      for connecting from Java to relational databases. The JDBC
standard was defined      by Sun Microsystems, allowing independent providers
to implement and extend      the standard with their own.


In addition to supporting the standard JDBC API, Oracle drivers
have   extensions      to support Oracle-specific datatypes and to enhance
performance.   For more      information about Oracle JDBC, refer the Useful   References
section in this document.
What are CLOBs?

Basically, LOBs (Large Objects) are designed to support
large unstructured data such as text, graphic images, still video clips,
full      motion video, and sound waveforms. A typical employee record
may   be a few      hundred bytes, but even small amounts of multimedia data
can   be thousands      of times larger. Oracle supports the following two
types   of LOBs:



  • Those stored in the database either in-line
    in the        table or in a separate segment or tablespace, such as BLOB(Binary
    LOB),        CLOB (Character LOB) and, NCLOB (National Character LOB).


    As the name signifies, BLOB holds binary data while the CLOB
    holds   textual        data and the NCLOB holds, character data that corresponds
    to the national        character set defined for the Oracle database.


  • Those stored as operating system files,
    such   as BFILEs.        

Managing CLOBs and BLOBs in JDBC is not very simple
when      compared to managing small amount of data. The way the CLOB and
the BLOB objects      are created and managed is different than a VARCHAR(String)
column. In fact,      Oracle extension classes are provided to support these
types objects in JDBC      like oracle.sql.CLOB,
oracle.sql.BLOB   
etc.
The new enhancements in Oracle JDBC 10g
promises
to simplify the insertion and retrieval techniques for the CLOBs using
the      standard APIs
. This document enumerates how easily the CLOB
data can      be handled in JDBC, by harnessing the new features of the
Oracle  JDBC 10g
driver.



Prerequisites



To work your way through this HowTo, it is necessary
to      have a basic understanding of the fundamental concepts of JDBC,
and  how to      use the JDBC APIs to connect to the database for the basic
CRUD(Create,  Read,      Update, and Delete)- the essential database operations.
In addition,  you need      to know the basic Oracle database concepts.



Software Requirements




  • Oracle
    Database
    10g
    .        You can download the database here
    .      

  • Oracle Database 10g
    JDBC Driver. This
    can  be downloaded      here
    .
  • JDK1.4.x or later that can be downloaded
    here
    .


How To Handle CLOBs Easily in JDBC?



Prior to Oracle JDBC 10g
, to manipulate the
CLOB      data in JDBC, Oracle extension class oracle.sql.CLOB
was used. But now, Oracle JDBC 10g
has a few enhancements that simplifies
the CLOB manipulation in JDBC applications. This enables handling of
large      data using some of the available standard APIs
, instead
of using the      Oracle extension classes. These could be thought as shortcuts
for inserting      and retrieving CLOB data from the database.
The enhanced standard APIs for manipulating CLOBs are
the      setString()
and getString()
of the PreparedStatement
and ResultSet
objects respectively. By
default, the method preparedStatement.setString()
will allow processing of the strings up to 32765 bytes. In order to
insert      data greater than 32765 bytes, a newly introduced Connection
property -
SetBigStringTryClob
can be set. This      forces the preparedStatement.setString()
to      use another
newly introduced method, OraclePreparedStatement.setStringForClob()
instead. This is actually done internally, transparent to the user.


Nevertheless, the newly introduced method OraclePreparedStatement.setStringForClob()
alone can also be used instead of the standard APIs.     This method   makes
the check on the data size internally again.

ResultSet.getString()
can still be
used  to read      the CLOB column. For the  getString()
and the      setString()
operations, the size
limit for the      string to be read or inserted is the one imposed by Java,
that is, a positive      int; the smallest being 0 or 1 byte.
Note: Do not use the setString()
to bind large data to VARCHAR and LONG database columns, since it may
truncate      the data or cause errors.



In summary, PreparedStatement.setString()
comes handy for processing the CLOB data, by just setting the Connection
property SetBigStringTryClob
.
However, handling      very large amounts of data this way may not be a
wise;  streaming the data      is a better alternative.


Following is the code snippet to set the Connection
property to process large data
using the standard APIs. Refer the full source        code in the file:
ClobManipulationIn10g.java



import java.sql.Connection;
import java.sql.DriverManager;
import oracle.jdbc.OracleDriver;
import java.util.Properties;
..........  
// Load the database details into the variables.
String url      = "jdbc:oracle:thin:@localhost:1521:orcl";
String user     = "scott";
String password = "tiger";
// Create the properties object that holds all database details
Properties props = new Properties();
props.put("user", user );
props.put("password", password);
props.put("SetBigStringTryClob", "true");

// Load the Oracle JDBC driver class.
DriverManager.registerDriver(new OracleDriver());     
// Get the database connection
Connection conn = DriverManager.getConnection( this.url, this.props );


The code snippet to create an Oracle database table
with        a CLOB column in it.




// SQL statement
CREATE TABLE clob_tab (clob_col CLOB);


Once the Connection
property - SetBigStringTryClob
is set,
use the standard preparedStatement.setString()
method for binding data more than 32765 bytes.


PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO clob_tab VALUES(?)");
// Read a big file(larger than 32765 bytes).
// Note: method readFile() not listed here.
// It can be any method that reads a file.
String str = this.readFile("bigFile.txt");
// The string data is automatically transformed into a CLOB and
// inserted into the database column.
// Make sure that the Connection property - 'SetBigStringTryClob' is
// set to true for the insert to happen.
pstmt.setString(1, str);
pstmt.executeUpdate();




Instead of the standard APIs, Oracle extension
APIs      can be used. OraclePreparedStatement.setStringForClob()
can be used for binding data greater than 32765 bytes.


import java.sql.*;
import java.io.*;
import java.util.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.*;
..........
// Create SQL query to insert CLOB data and other columns in the database.
String sql = "INSERT INTO clob_tab VALUES(?)";
// Read a big file(larger than 32765 bytes).
// Note: method readFile() not listed here.
// It can be any method that reads a file.
String str = this.readFile("bigFile.txt");
// Create the OraclePreparedStatement object
opstmt = (OraclePreparedStatement)conn.prepareStatement(sql);

// Use the new method to insert the CLOB data (for data greater or lesser than 32 KB)
opstmt.setStringForClob(1,str);


// Execute the OraclePreparedStatement
opstmt.executeUpdate();
...........




Following is the code snippet that demonstrates the
use        of the standard ResultSet.getString()
method,        enhanced now to read more than 32765 bytes:


.....
// Create a PreparedStatement object
PreparedStatement pstmt = null;
// Create a ResultSet to hold the records retrieved.
ResultSet rset = null;
.......

// Create SQL query statement to retrieve records having CLOB data from
// the database.
String sqlCall = "SELECT clob_col FROM clob_tab";
pstmt= conn.prepareStatement(sqlCall);
// Execute the PrepareStatement
rset = pstmt.executeQuery();
String clobVal = null;
// Get the CLOB value larger than 32765 bytes from the resultset
while (rset.next()) {
clobVal = rset.getString(1);
System.out.println("CLOB length: "+clobVal.length());     
}




Running the Sample Java Application



  • Copy the sample Class file ClobManipulationIn10g.java
    in a directory, say
    for example, clobs
    .

  • From the clobs
    directory,       set the environment variable CLASSPATH to include the following:


    • Include the JDBC driver class; use ojdbc14.jar
      with JDK 1.4.x / use  classes12.jar/zip
      with JDK 1.3.x

    • Include the current directory(.
      )
      in  the CLASSPATH.



  • Create the table 'clob_tab' in an Oracle database
    under      a user say, scott. Refer the code snippet
    for more      details.

  • Edit the file ClobManipulationIn10g.java
    to configure your database details.



    • Change the following lines in the file
      in  the         main()
      method.
      // Load the database details into the variables.

      String dbUrl = "jdbc:oracle:thin:@<database host machine>:<port>:<SID>
      ";

      clobManipulationIn10g.user = "scott
      "; // Replace the
      username where the table 'clob_tab' was created.

      clobManipulationIn10g.password = "tiger
      "; // Replace
      the password of the username.

      Replace the values of:
      <database host machine>
      where the Oracle database
      is installed.

      <port>

      port where the database TNS listener listening.
      The default is 1521.

      <SID>

      the SID of the database.



  • Save the file. Compile the Java file using:
    javac -d . ClobManipulationIn10g.java

  • Run the class using the following command.
    Pass  a file      name with the complete path as the parameter value for
    <fileName>.  For      testing, use a file which is >32 KB of size.

    java oracle.otnsamples.jdbc.ClobManipulationIn10g
    "<fileName>"


      For example, java oracle.otnsamples.jdbc.ClobManipulationIn10g
    "d:\test\bigFile.txt"


    Depending on the size of the file(say for example, 40kb) that
    was   read,        the output will be like the following:

       CLOB length:
    40000

  
  orginal site:http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jdbc/clob10g/handlingclobsinoraclejdbc10g.html
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-250824-1-1.html 上篇帖子: Oracle Bulk 与 性能优化 说明 下篇帖子: oracle学习笔记(一)之逻辑结构和连接
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表