`
yaya_wiscom
  • 浏览: 48126 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

使用JDBC存入数据库Clob字段

阅读更多

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

 

public static Clob stringToClob(String str) {
	if (null == str)
		return null;
	else {
		try {
			java.sql.Clob c = new javax.sql.rowset.serial.SerialClob(str
					.toCharArray());
			return c;
		} catch (Exception e) {
			return null;
		}
	}
}

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

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

 

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

 

String saveSql = " INSERT INTO t_xxts_xx(wid,xh,xxmc,xxnr,sffsyj,sffsdx,sffsxtxx,fsrgh,cjrq,sffs) "
				+ " VALUES( '" + wid + "','" + wid + "','[研究生任务计划]"
				+ calendar[0]
				+ "年 "
				+ calendar[1]
				+ "月 第"
				+ calendar[2]
				+ "周 任务统计',"
				+ " EMPTY_CLOB(),'1','0','0','XT',to_char(SYSDATE,'yyyy-mm-dd hh24:mi:ss'),'1') ";

 

2、Update Clob字段

 

String update_sql = "select xxnr from t_xxts_xx where wid='"+wid+"' for update";
  

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

 

   try {
		       Connection conn = DbUtil.getSysDbConnection();
			conn.setAutoCommit(false);
			conn.createStatement().executeUpdate(saveSql);

			ResultSet rs = conn.createStatement().executeQuery(update_sql);
			if (rs.next()) {
				/* 取出此CLOB对象 */
				oracle.sql.CLOB clob = null;
				clob = (oracle.sql.CLOB) rs.getClob("xxnr");
				/* 向CLOB对象中写入数据 */
				BufferedWriter out = new BufferedWriter(clob
						.getCharacterOutputStream());
				try {
					Logger.debug("str=" + sb.toString());
					out.write(sb.toString());
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					Logger.error(e);
					throw new SQLException(e);
				}
			}
			rs.close();
			conn.commit();
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
 

 

如此这般,终于将大字符串存入了数据库中的Clob字段中。

 

4
0
分享到:
评论
1 楼 jeloo 2013-01-29  

相关推荐

Global site tag (gtag.js) - Google Analytics