自定义更新类提交超长字段串

业务背景:

西光集团的西安北方光电有限公司西光信息系统项目使用oracle8 作为数据库,当存储超过4K长度的字符串时报错,oracle提供的字符串字段的长度最长为4K,客户又需要完全的将超过4K的字符串保存到数据库,经过我们的分析,只能是修改字段类型,将varchar24000)的字段改为clob字段。

处理方案:

处理方案有两种,分别如下:

1:使用自定义更新类,将数据源名,字段名,数据值,主键等作为参数传到自定义更新类,完成大字段的数据录入。

2:提出产品修改需求,更新属性中增加更新clob字段,最终产品中增加了这个方法,但是只能在oracle数据库使用

由于新增的功能只能在oracle中使用,所以如果有其他数据库需要使用clob字段存储长字符串时,大家可以参考方案1中写法。

自定义更新类方法

由于代码比较长,下面仅列出步骤,具体使用时可参考附件代码。

报表设计

如下图所示:

注意:

1) 数据表字段与单元格一一对应,不需要提交的单元格可以不设置

2) CLOB字段可以有多个

3) 最后三个参数按顺序分别为主键,数据表名,数据源名

4) 主键可以有多个

代码片段

1) 首先判断是更新语句还是插入语句

String isIn = “select count(*) from “ + tableName + ” where “

+ getWhere(idNames, cv, types);

ResultSet isInCount = stmt.executeQuery(isIn);

if (isInCount.next()) {

m = isInCount.getInt(1);

}

1是更新,否则是插入数据

2) 如果是插入语句,执行insert语句

String sql = “insert into “ + tableName + ” values “

+ getSome(types);

System.out.println(sql);

pstmt1 = con.prepareStatement(sql);

如果是CLOB字段,插入oracle oracle.sql.CLOB.empty_lob()对象

pstmt1.setClob(n, oracle.sql.CLOB.empty_lob());

3) 查找CLOB字段出来,并将字符串通过clobputString方法设置到CLOB对象中

String sql2 = “select “ + getClobS(clobNames) + ” from “

+ tableName + ” where “ + getWhere(idNames, cv, types)

+ ” for update”;

System.out.println(sql2);

ResultSet rs = stmt.executeQuery(sql2);

ResultSetMetaData md = rs.getMetaData();

int cols = md.getColumnCount();

if (rs.next()) {

hmc.clear();

for (int i = 1; i <= cols; i++) {

CLOB clob = (CLOB) rs.getClob(i);

String clobName = md.getColumnName(i);

Object clobValues = cv.get(clobName);

if (clobValues == null) {

hmc.put(i, oracle.sql.CLOB.empty_lob());

} else {

clob. putString (1, clobValues.toString());

}

hmc.put(i, clob);

}

4) 更新 CLOB字段

String upClob = “update “ + tableName + ” set “

+ setUpClob(clobNames) + ” where “

+ getWhere(idNames, cv, types);

PreparedStatement pstmt = con.prepareStatement(upClob);

for (int i = 1; i <= hmc.size(); i++) {

pstmt.setClob(i, hmc.get(i));

}

pstmt.executeUpdate();

5) 如果是更新操作,步骤类似,不再单独列出

6) 主要方法

a) 获取连接 getCon(String databaseName)

b) 获取字段数据类型和字段名称生成hashmap getType(Connection con, String tableName)

c) 获取 字段和valuehashmap getCV(Object[] o)

d) 动态拼更新语句,where语句等