Chinaunix首页 | 论坛 | 博客
  • 博客访问: 147126
  • 博文数量: 27
  • 博客积分: 2011
  • 博客等级: 大尉
  • 技术积分: 332
  • 用 户 组: 普通用户
  • 注册时间: 2006-06-02 16:13
文章分类

全部博文(27)

文章存档

2009年(18)

2008年(9)

我的朋友

分类: Oracle

2009-11-17 15:29:13

创建测试表
create table CLOB_TEST(ID number(10), CLOB_TEXT CLOB)
 

import java.sql.*;
import java.io.OutputStream;
import java.io.Writer;
import java.io.Reader;

// create table CLOB_TEST(ID number(10), CLOB_TEXT CLOB)

public class ClogTest {

    public static void main(String[] args) throws Exception{
        Class.forName("oracle.jdbc.driver.OracleDriver");
        
        Connection conn = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:zhongyj", "scott", "tiger");

        // 每次执行时,要修改第二个参数id

        insertClob(conn, 4);
        readClob(conn, 4);
        
        conn.close();
    }
    
    static void insertClob(Connection conn, int id) throws Exception {
        conn.setAutoCommit(false);
        PreparedStatement ps = conn.prepareStatement("insert into CLOB_TEST(ID, CLOB_TEXT) values(?,empty_clob())");
        ps.setInt(1, id);
        ps.executeUpdate();
        
        ps= conn.prepareStatement("select CLOB_TEXT from CLOB_TEST where ID=? for update");
        ps.setInt(1, id);
        
        ResultSet rs = ps.executeQuery();
        Clob clob = null;
        
        if(rs.next()) {
            clob = rs.getClob(1);
        }
        
        // 这一段往CLOB_TEXT字段存入CLOB_TEXT_CONTENT

        String str = "Write in String: Hello Jdbc CLOB";
        clob.setString(10, str); // 第一个参数是从第几个字符开始写

        
//        // 这一段往CLOB_TEXT字段存入CLOB_TEXT_CONTENT

//        Writer wr = clob.setCharacterStream(10); // 参数是从第几个字符开始写

//        wr.write("Write in Writer");

//        wr.flush();

//        wr.close();

        
        rs.close();
        conn.commit();
        ps.close();
    }

    static void readClob(Connection conn, int id) throws Exception{
        PreparedStatement ps = conn.prepareStatement("select CLOB_TEXT from CLOB_TEST where ID=?");
        ps.setInt(1, id);
        
        ResultSet rs = ps.executeQuery();
        
        if(rs.next()) {
            Clob clob = rs.getClob("CLOB_TEXT");
            Reader rd = clob.getCharacterStream();
            char [] str = new char[12];
            while(rd.read(str) != -1) {
                System.out.print(str);
            }
        }
    }
}


阅读(6517) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~