JAVA代码如何读取、写入、更新CLOB字段呢?

书欣 Java经验 发布时间:2022-10-10 17:30:32 阅读数:3296 1
下文笔者讲述使用Java代码读取,写入,更新CLOB字段的方法分享,如下所示
例:

建表

 
create table t_clob(
		id varchar2(32) primary key,
		clobfield CLOB
		);

/**
 * 读取CLOB字段的代码示例 
 */
public void readClob() {
	//自定义的数据库连接管理类 
	Connection conn = DbManager.getInstance().getConnection();
	try {
		PreparedStatement stat = conn
				.prepareStatement("select clobfield from t_clob where id='1'");
		ResultSet rs = stat.executeQuery();
		if (rs.next()) {
			oracle.sql.CLOB clob = (oracle.sql.CLOB) rs
					.getClob("clobfield");
			String value = clob.getSubString(1, (int) clob.length());
			System.out.println("CLOB字段的值:" + value);
		}
		conn.commit();
	} catch (SQLException e) {
		e.printStackTrace();
	}

	DbManager.getInstance().closeConnection(conn);
}

/**
 * 写入、更新CLOB字段的代码示例 
 */
public void writeClob() {
	//自定义的数据库连接管理类 
	Connection conn = DbManager.getInstance().getConnection();
	try {
		conn.setAutoCommit(false); 
		PreparedStatement stat = conn
				.prepareStatement("insert into t_clob (id,clobfield) values(sys_guid(),?)");
		String clobContent = "This is a very very long string";
		StringReader reader = new StringReader(clobContent);
		stat.setCharacterStream(1, reader, clobContent.length());
		stat.executeUpdate();

		stat = conn
				.prepareStatement("select clobfield from t_clob where id='1' for update");
		ResultSet rs = stat.executeQuery();
		if (rs.next()) {
			oracle.sql.CLOB clob = (oracle.sql.CLOB) rs
					.getClob("clobfield");
			Writer outStream = clob.getCharacterOutputStream();
			char[] c = clobContent.toCharArray();
			outStream.write(c, 0, c.length);
			outStream.flush();
			outStream.close();
		}
		conn.commit();
	} catch (SQLException | IOException e) { 
		e.printStackTrace();
	}

	DbManager.getInstance().closeConnection(conn);
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202210/16653942864605.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者