db2 clob

由于项目的需要.用到了大字段Clob.以下是读取方法

  第一种:

  Clob clob = rs.getClob(“remark”);//java.sql.Clob

  String detailinfo = “”;

  if(clob != null){

  detailinfo = clob.getSubString((long)1,(int)clob.length());

  }

  第二种:

  Clob clob = rs.getClob(“remark”);//java.sql.Clob

  int i = 0;

  if(clob != null){

  InputStream input = clob.getAsciiStream();

  int len = (int)clob.length();

  byte by[] = new byte[len];

  while(-1 != (i = input.read(by, 0, by.length))){

  input.read(by, 0, i);

  }

  detailinfo = new String(by, “utf-8″);

  }

  第三种:

  Clob clob = rs.getClob(“remark”);//java.sql.Clob

  String value=”";

  String line=”";

  if(clob!=null){

  Reader reader=((oracle.sql.CLOB)clob).getCharacterStream();

  BufferedReader br=new BufferedReader(reader);

  while((line=br.readLine())!=null)

  {

  value += line + “\r\n”;

  }

  }

  第一种方法代码量少,且能避免中文乱码问题;第二种方法与第一种方法效率差不多,也是常使用的一种方法;第三种方法效率极低,如果数据比较大的话建议不要使用。

  Clob与String之间相互转换的方法如下:

  /**

  * clob类型转换为String



  * @param clob

  * @return



  * String

  */

  public static String ClobToString(Clob clob){

  String clobS="";

  try {

  clobS= clob.getSubString(1, (int)clob.length());

  } catch (SQLException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  return clobS;

  }

  /**

  * String类型转换为Clob



  * @param clobs

  * @return



  * Clob

  */

  public static Clob StringToClob(String clobs){

  Clob clob=null;

  try {

  clob=new SerialClob(clobs.toCharArray());

  } catch (SerialException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  } catch (SQLException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  }

  return clob;

  }

  另外特别注意的是:Clob是以流的形式读取的,所以在未完全读出来的时候,数据库连接是不能关闭的.这也和数据库的类型及驱动有关.目前来看对DB2中的大字段来进行读取的时候数据库连接是不能关闭的

猜你喜欢

转载自xuxiangpan888.iteye.com/blog/2086002
db2