ねら~ITエンジニア雑記

やきうのお兄ちゃんが綴るOracle Databaseメインのブログ

CLOBをSELECTして表示するjavaソース・サンプル(Oracle Database + java)

下記サイトを参考にしながら書いてみたやで。彡(゚)(゚)
ワイ java は不慣れなんで、そこは勘弁やで彡(-)(-)

SELECT文サンプル
http://java-reference.com/java_db_select.html

インタフェースClob
https://docs.oracle.com/javase/jp/8/docs/api/java/sql/Clob.html

表定義は下記彡(゚)(゚)

SQL> DESC LOB_TBL
 Name          Null?    Type
 ------------- -------- ----------------------------
 LOB_ID        NOT NULL NUMBER
 LOB_DATA               CLOB

javaソースのサンプルは下記彡(゚)(゚)

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Clob;

public class LOBSelectSample {
    public static void main(String[] args) throws Exception{
        //initialize
        System.out.println("Init...");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Clob cl = null;

        //DB connection info
        String path = "jdbc:oracle:thin:@localhost:1521:orcl";  //path
        String id = "xxxxxxxx";  //ID
        String pw = "yyyyyyyy";  //password

        try{
            //JDBC Driver
            Class.forName("oracle.jdbc.driver.OracleDriver");

            //DB Connect
            System.out.println("Connect...");
            conn = DriverManager.getConnection(path, id, pw);

            //SELECT
            System.out.println("Select...");
            ps = conn.prepareStatement("SELECT * FROM LOB_TBL");
            rs = ps.executeQuery();

            //Column count
            int colCount = rs.getMetaData().getColumnCount();
            System.out.println("Get Column:" + colCount);

            //Output
            while (rs.next()) {
                System.out.print(rs.getInt("LOB_ID"));
                System.out.println();
                cl = rs.getClob("LOB_DATA");
                if (cl != null) {
                    System.out.print(cl.getSubString(1, (int)cl.length()));
                    //System.out.print(cl.getSubString(1, 2097152));
                }
                System.out.println();
            }
        } catch(Exception ex) {
            //Exception
            ex.printStackTrace();  //Error
        } finally {
            //Close
            if(rs != null) rs.close();
            if(ps != null) ps.close();
            if(conn != null) conn.close();
        }
    }
}

コンパイル、漢は黙って生javaや!彡(゚)(゚)

javac -classpath .:${ORACLE_HOME}/jdbc/lib/ojdbc8.jar LOBSelectSample.java

実行コマンド、漢は黙っt(ry

java -classpath .:${ORACLE_HOME}/jdbc/lib/ojdbc8.jar LOBSelectSample

実行結果、LOB_DATA列に突っ込んどいたSQLテキストが出て来たやで彡(^)(^)

Init...
Connect...
Select...
Get Column:2
1

2
with …
:
(中略)
:
… from dual