示例#1
0
    private void doPreparedStatement(
        PreparedStatement ps, DbDialect dbDialect, LobCreator lobCreator, EventData data)
        throws SQLException {
      EventType type = data.getEventType();
      // 注意insert/update语句对应的字段数序都是将主键排在后面
      List<EventColumn> columns = new ArrayList<EventColumn>();
      if (type.isInsert()) {
        columns.addAll(data.getColumns()); // insert为所有字段
        columns.addAll(data.getKeys());
      } else if (type.isDelete()) {
        columns.addAll(data.getKeys());
      } else if (type.isUpdate()) {
        boolean existOldKeys = !CollectionUtils.isEmpty(data.getOldKeys());
        columns.addAll(data.getUpdatedColumns()); // 只更新带有isUpdate=true的字段
        columns.addAll(data.getKeys());
        if (existOldKeys) {
          columns.addAll(data.getOldKeys());
        }
      }
      for (int i = 0; i < columns.size(); i++) {
        int paramIndex = i + 1;
        EventColumn column = columns.get(i);
        int sqlType = column.getColumnType();

        // 获取一下当前字段名的数据是否必填
        Table table = dbDialect.findTable(data.getSchemaName(), data.getTableName());
        Map<String, Boolean> isRequiredMap = new HashMap<String, Boolean>();
        for (Column tableColumn : table.getColumns()) {
          isRequiredMap.put(StringUtils.lowerCase(tableColumn.getName()), tableColumn.isRequired());
        }

        Boolean isRequired = isRequiredMap.get(StringUtils.lowerCase(column.getColumnName()));
        if (isRequired == null) {
          throw new ClaveException(
              String.format(
                  "column name %s is not found in Table[%s]",
                  column.getColumnName(), table.toString()));
        }

        Object param =
            SqlUtils.stringToSqlValue(
                column.getColumnValue(), sqlType, isRequired, dbDialect.isEmptyStringNulled());
        try {
          switch (sqlType) {
            case Types.CLOB:
              lobCreator.setClobAsString(ps, paramIndex, (String) param);
              break;

            case Types.BLOB:
              lobCreator.setBlobAsBytes(ps, paramIndex, (byte[]) param);
              break;

            default:
              StatementCreatorUtils.setParameterValue(ps, paramIndex, sqlType, null, param);
              break;
          }
        } catch (SQLException ex) {
          logger.error(
              "## SetParam error , [table={}, sqltype={}, value={}]",
              new Object[] {data.getSchemaName() + "." + data.getTableName(), sqlType, param});
          throw ex;
        }
      }
    }
 @Override
 protected void setParameterInternal(
     PreparedStatement ps, int index, Object value, String jdbcType, LobCreator lobCreator)
     throws SQLException {
   lobCreator.setClobAsString(ps, index, (String) value);
 }