---
title: "java读写clob"
author: "faulware"
date: "2011-09-06T19:26:24Z"
tags: []
categories: ["编程语言"]
slug: "java-clob"
draft: false
lastmod: "2011-09-06T19:26:24Z"
id: 1166957
url: "https://faulware.iteye.com/blog/1166957"
---

从数据库中读取clob值
 public String clob2String(Clob clob)
	{
		
		StringBuffer retValue=new StringBuffer();
		if(clob!=null)
		{
		try {
			Reader reader=clob.getCharacterStream();
			BufferedReader in=new BufferedReader(reader);
			String s=in.readLine();
			while(s!=null)
			{
				retValue.append(s);
				s=in.readLine();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}catch (IOException e) {
		}
		}
		return retValue.toString();
	}

将string存储到数据库
public void writeClob(String s)
	{
		Connection conn=null;
		ResultSet rs=null;
		try {
			java.sql.Statement stmt=conn.createStatement();
			boolean flag=conn.getAutoCommit();
			conn.setAutoCommit(false);
			String sql="update tableName set clobCloumn=empty_Clob()";
			String updateSql="select clobCloumn from tableName for update";
			stmt.executeUpdate(sql);
			rs=stmt.executeQuery(updateSql);
			while(rs.next())
			{
				Writer writer=rs.getClob("clobCloumn").setCharacterStream(1);
				writer.write(s);
				writer.flush();
				writer.close();
			}
			
			conn.commit();
			conn.setAutoCommit(flag);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}