当前位置:   article > 正文

PreparedStatement的setString与setObject关于传入为null值时替换_setstring为空

setstring为空

报错信息:

org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [ INSERT INTO M_OP (ID,AG,FLAG) VALUES(?,?,?)]; .....Incorrect decimal value: 'null' for column 'AG' at row 1 .... nested exception is java.sql.BatchUpdateException:

应用场景: 应用中通过jdbc从远程Oracle数据源读取A表数据,再通过jdbc插入Mysql数据库B张表。因为A、B两表字段均可为null。导致从A读出数据为null时,使用setString(int parameterIndex, String x)null值无法转换,导致后续sql执行失败,但是替换为void setObject(int parameterIndex, Object x)正常转换。

代码如下:

  1. public List<Map<String, Object>> getDetail(String No) {
  2. String sql = " SELECT ID, AG,'01' AS FLAG FROM AG_DETAIL WHERE FLAG ='02' AND NO = ? ";
  3. return jdbcOracle.queryForList(sql, No);
  4. }
  5. public int[] insDetail(final List<Map<String, Object>> list) {
  6. String sql = " INSERT INTO M_OP (ID,AG,FLAG,) VALUES(?,?,?)";
  7. return jdbcMysql.batchUpdate(sql, new BatchPreparedStatementSetter() {
  8. @Override
  9. public void setValues(PreparedStatement ps, int i) throws SQLException {
  10. Map<String, Object> map = list.get(i);
  11. ps.setString(1, String.valueOf(map.get("ID")));
  12. ps.setString(2, String.valueOf(map.get("AG")));
  13. ps.setString(3, String.valueOf(map.get("FLAG")));
  14. }
  15. @Override
  16. public int getBatchSize() {
  17. return list.size();
  18. }
  19. });
  20. }

应用中调用:insDetail(getDetail(no));

解决:把setString(int parameterIndex, String x)替换为setObject(int parameterIndex, Object x).

代码如下:

  1. public int[] insDetail(final List<Map<String, Object>> list) {
  2. String sql = " INSERT INTO M_OP (ID,AG,FLAG,) VALUES(?,?,?)";
  3. return jdbcMysql.batchUpdate(sql, new BatchPreparedStatementSetter() {
  4. @Override
  5. public void setValues(PreparedStatement ps, int i) throws SQLException {
  6. Map<String, Object> map = list.get(i);
  7. ps.setObject(1, map.get("ID"));
  8. ps.setObject(2, map.get("AG"));
  9. ps.setObject(3, map.get("FLAG"));
  10. }
  11. @Override
  12. public int getBatchSize() {
  13. return list.size();
  14. }
  15. });
  16. }



本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
  

闽ICP备14008679号