使用JDBC存入数据库Clob字段



使用JDBC存入数据库Clob字段。

这两天用Java任务管理系统Quartz做了一个定时发送邮件的事情。具体应用是这样的:我们需要在每天填写的任务系统中使用一张配置表,来设置提醒邮件的发送频率和日期。实现过程中前面还算比较顺利,最后在向T_XXTS_XX表中插入待发送邮件的HTML字符串时发生了错误,原因就是数据库中是Clob大字段而后台待存入的数据是String类型的字符串。我的第一反应是想办法将String类型的字符串转换为java.sql.Clob类型的数据。所在在网上找了一些资料,个人感觉比较可行的转换方式是如下的代码:

 

Java代码  收藏代码
  1. public static Clob stringToClob(String str) {
  2.     if (null == str)
  3.         return null;
  4.     else {
  5.         try {
  6.             java.sql.Clob c = new javax.sql.rowset.serial.SerialClob(str
  7.                     .toCharArray());
  8.             return c;
  9.         } catch (Exception e) {
  10.             return null;
  11.         }
  12.     }
  13. }

但是,悲剧的事情发生的,由于我们公司的基础平台是建立在JDK1.4版本之上的,而我本地的JRE环境确实JDK1.6的,所以就会导致我的代码编译器没有报错,但是static方法就是无法返回值。所以在这里需要注意一下的就是SerialClob这个转换类是在JDK1.5+才引入的类,早期的JDK版本中并没有这个类。

通过在网上的学习终于学会了使用输出流的方式将大字符串写入Clob中存入数据库,具体的实现方式如下:

 

1、首先我们先使用EMPTY_CLOB()向数据库中插入空值;

 

Java代码  收藏代码
  1. String saveSql = ” INSERT INTO t_xxts_xx(wid,xh,xxmc,xxnr,sffsyj,sffsdx,sffsxtxx,fsrgh,cjrq,sffs) ”
  2.                 + ” VALUES( ’” + wid + ”‘,’” + wid + ”‘,’[研究生任务计划]“
  3.                 + calendar[0]
  4.                 + ”年 ”
  5.                 + calendar[1]
  6.                 + ”月 第”
  7.                 + calendar[2]
  8.                 + ”周 任务统计’,”
  9.                 + ” EMPTY_CLOB(),’1′,’0′,’0′,’XT’,to_char(SYSDATE,’yyyy-mm-dd hh24:mi:ss’),’1′) ”;


 

2、Update Clob字段

 

Java代码  收藏代码
  1. String update_sql = ”select xxnr from t_xxts_xx where wid=’”+wid+”‘ for update”;

使用JDBC获取Connection之后我们要将数据库的提交方式手动的修改为false

 

Java代码  收藏代码
  1.  try {
  2.        Connection conn = DbUtil.getSysDbConnection();
  3.     conn.setAutoCommit(false);
  4.     conn.createStatement().executeUpdate(saveSql);
  5.     ResultSet rs = conn.createStatement().executeQuery(update_sql);
  6.     if (rs.next()) {
  7.         /* 取出此CLOB对象 */
  8.         oracle.sql.CLOB clob = null;
  9.         clob = (oracle.sql.CLOB) rs.getClob(“xxnr”);
  10.         /* 向CLOB对象中写入数据 */
  11.         BufferedWriter out = new BufferedWriter(clob
  12.                 .getCharacterOutputStream());
  13.         try {
  14.             Logger.debug(“str=” + sb.toString());
  15.             out.write(sb.toString());
  16.             out.flush();
  17.             out.close();
  18.         } catch (IOException e) {
  19.             e.printStackTrace();
  20.             Logger.error(e);
  21.             throw new SQLException(e);
  22.         }
  23.     }
  24.     rs.close();
  25.     conn.commit();
  26.     conn.setAutoCommit(true);
  27. } catch (SQLException e) {
  28.     e.printStackTrace();
  29. } finally {
  30.     try {
  31.         conn.close();
  32.     } catch (SQLException e) {
  33.         e.printStackTrace();
  34.     }
  35. }

 http://yaya-wiscom.iteye.com/blog/1100221