java.sql.Clob 对象转 String

 转换类的源码:

package com.lingran.dayang.utils;

import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;

public class Clob2String
{
	/**
	 * 数据库Clob对象转换为String
	 */
	@SuppressWarnings("unused")
	public static String clobToString(Clob clob)
	{
		if(clob == null) {
			return null;
		}
		try
		{
			Reader inStreamDoc = clob.getCharacterStream();
			
			char[] tempDoc = new char[(int) clob.length()];
			inStreamDoc.read(tempDoc);
			inStreamDoc.close();
			return new String(tempDoc);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (SQLException es)
		{
			es.printStackTrace();
		}
		
		return null;
	}

}


测试代码: 需要JUnit 4.x

package com.lingran.dayang.utils.test;

import java.sql.Clob;

import javax.sql.rowset.serial.SerialClob;

import org.junit.Test;

import com.lingran.dayang.utils.Clob2String;

import static org.junit.Assert.*;

public class Clob2StringTest {
	
	public @Test void withNotNullClob() {
		String value = "lvjian";
		Clob clob = null;
		try {
			clob = new SerialClob(value.toCharArray());
		} catch (Exception e) {
			fail("fail in create Clob data..");						
		}
		
		assertNotNull(clob);
		String ret = Clob2String.clobToString(clob);
		assertNotNull(ret);
		assertEquals(ret, value);
	}
	
	public @Test void withNull() {
		Clob clob = null;
		String ret = Clob2String.clobToString(clob);
		assertNull(ret);
	}
	
	public @Test void withEmptyValue() {
		Clob clob = null;
		String value = "";
		
		try {
			clob = new SerialClob(value.toCharArray());
		} catch (Exception e) {
			fail("fail in create Clob data..");	
		}
		
		String ret = Clob2String.clobToString(clob);
		assertNotNull(ret);
		assertEquals(ret, "");
	}
}

你可能感兴趣的:(java,sql,JUnit)