Java Code Examples for java.sql.Types#CLOB

The following examples show how to use java.sql.Types#CLOB . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Column.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns the type of the given type as simple
 * string representation, either "i" for intergers,
 * "s" for strings and "d" for date types
 *
 * @param cType the column type
 * @return the simple type string represenation
 */
static public int getTypeID (int cType) {
	switch (cType) {
	case Types.DECIMAL:
	case Types.NUMERIC:
	case Types.DOUBLE:
	case Types.FLOAT:
	case Types.REAL:
	case Types.BIGINT:
	case Types.INTEGER:
	case Types.SMALLINT:
	case Types.TINYINT:
		return NUMERIC;
	case Types.CHAR:
	case Types.VARCHAR:
	case Types.BLOB:
	case Types.CLOB:
		return STRING;
	case Types.DATE:
	case Types.TIME:
	case Types.TIMESTAMP:
		return DATE;
	default:
		return UNSET;
	}
}
 
Example 2
Source File: DVDStoreResultSet.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Clob getClob(int columnIndex) throws SQLException {
  if (columnIndex > 0 && columnIndex <= this.numColumns) {
    final TableMetaData metadata = getMetaData();
    if (metadata.getColumnType(columnIndex) != Types.CLOB) {
      throw dataConversionException(metadata.getColumnTypeName(columnIndex),
          "Clob", columnIndex);
    }
    try {
      final DataValueDescriptor dvd;
      if (this.currentRowDVDs != null) {
        dvd = this.currentRowDVDs[columnIndex - 1];
      }
      else if (this.pvs != null) {
        dvd = this.pvs.getParameter(columnIndex - 1);
      }
      else {
        throw noCurrentRow();
      }
      if (dvd != null && !dvd.isNull()) {
        this.wasNull = false;
        return HarmonySerialClob.wrapChars(((SQLChar)dvd).getCharArray(true));
      }
      else {
        this.wasNull = true;
        return null;
      }
    } catch (StandardException se) {
      throw Util.generateCsSQLException(se);
    }
  }
  else {
    throw invalidColumnException(columnIndex);
  }
}
 
Example 3
Source File: SqlLogFilter.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author yang.zhipeng <br>
 * @taskId <br>
 * @param statement <br>
 * @return <br>
 */
private String getExcuteSql(final StatementProxy statement) {
    String sqlStr = statement.getBatchSql();
    if (statement instanceof PreparedStatementProxy) {
        for (JdbcParameter parameter : statement.getParameters().values()) {
            int sqlType = parameter.getSqlType();
            Object value = parameter.getValue();
            String tempValue;
            switch (sqlType) {
                case Types.NULL:
                    tempValue = "NULL";
                    break;
                case Types.CLOB:
                case Types.CHAR:
                case Types.VARCHAR:
                    tempValue = new StringBuilder().append('\'').append(value).append('\'').toString();
                    break;
                default:
                    tempValue = String.valueOf(value);
                    break;
            }
            sqlStr = StringUtils.replaceOnce(sqlStr, "?", tempValue);
        }
    }

    return sqlStr;
}
 
Example 4
Source File: Type1BlobCollectionConversionHandler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Object getValidateSource(String id, ResultSet rs) throws SQLException
{
	ResultSetMetaData metadata = rs.getMetaData();
	byte[] rv = null;
	switch(metadata.getColumnType(1))
	{
	case Types.BLOB:
		Blob blob = rs.getBlob(1);
		if(blob != null)
		{
			rv = blob.getBytes(1L, (int) blob.length());
		}
		else
		{
			log.info("getValidateSource(" + id + ") blob is null" );
		}
		break;
	case Types.CLOB:
		Clob clob = rs.getClob(1);
		if(clob != null)
		{
			rv = clob.getSubString(1L, (int) clob.length()).getBytes();
		}
		break;
	case Types.CHAR:
	case Types.LONGVARCHAR:
	case Types.VARCHAR:
		rv = rs.getString(1).getBytes();
		break;
	case Types.BINARY:
	case Types.VARBINARY:
	case Types.LONGVARBINARY:
		rv = rs.getBytes(1);
		break;
	}
	return rv;
}
 
Example 5
Source File: Cursor.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
final Reader getCharacterStream(int column)
            throws SQLException
    {
        switch (jdbcTypes_[column - 1]) {
            case Types.CLOB:
                throw new UnsupportedOperationException();
//                ClientClob c = getClobColumn_(column, agent_, false);
//                if (c.isLocator()) {
//                    ClobLocatorReader reader
//                            = new ClobLocatorReader(agent_.connection_, c);
//                    return new BufferedReader(reader);
//                } else {
//                    return c.getCharacterStreamX();
//                }
            case Types.CHAR:
                return new StringReader(get_CHAR(column));
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                return new StringReader(get_VARCHAR(column));
            case Types.BINARY:
                return new InputStreamReader(
                    new ByteArrayInputStream(
                        get_CHAR_FOR_BIT_DATA(column)), UTF_16BE);
            case Types.VARBINARY:
            case Types.LONGVARBINARY:
                return new InputStreamReader(
                    new ByteArrayInputStream(
                        get_VARCHAR_FOR_BIT_DATA(column)), UTF_16BE);
            case Types.BLOB:
                return new InputStreamReader(getBinaryStream(column), UTF_16BE);
            default:
                throw coercionError( "java.io.Reader", column );
            }
    }
 
Example 6
Source File: HiveTypes.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 5 votes vote down vote up
/**
 * Given JDBC SQL types coming from another database, what is the best
 * mapping to a Hive-specific type?
 */
public static String toHiveType(int sqlType) {

    switch (sqlType) {
        case Types.INTEGER:
        case Types.SMALLINT:
            return "INT";
        case Types.VARCHAR:
        case Types.CHAR:
        case Types.LONGVARCHAR:
        case Types.NVARCHAR:
        case Types.NCHAR:
        case Types.LONGNVARCHAR:
        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
        case Types.CLOB:
            return "STRING";
        case Types.NUMERIC:
        case Types.DECIMAL:
        case Types.FLOAT:
        case Types.DOUBLE:
        case Types.REAL:
            return "DOUBLE";
        case Types.BIT:
        case Types.BOOLEAN:
            return "BOOLEAN";
        case Types.TINYINT:
            return "TINYINT";
        case Types.BIGINT:
            return "BIGINT";
        default:
      // TODO(aaron): Support BINARY, VARBINARY, LONGVARBINARY, DISTINCT,
      // BLOB, ARRAY, STRUCT, REF, JAVA_OBJECT.
      return null;
    }
}
 
Example 7
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Converts an ODA data type to its corresponding Java class,
 * as defined by the {@link DataTypeUtil} utility.
 * @param odaDataType	an ODA data type code
 * @return	the Java class that corresponds to the specified ODA data type
 * @throws IllegalArgumentException	if the specified ODA data type 
    *              is not a supported type
 */
public static Class toTypeClass( int odaDataType )
{
	final String methodName = "toTypeClass";		 //$NON-NLS-1$

       Class fieldClass = null;
       try
       {
           fieldClass = org.eclipse.birt.core.data.DataTypeUtil
                   .toOdiTypeClass( odaDataType );
       }
       catch( BirtException e )
       {
		String localizedMessage = 
			DataResourceHandle.getInstance().getMessage( ResourceConstants.UNRECOGNIZED_ODA_TYPE, 
			                                             new Object[] { Integer.valueOf( odaDataType ) } );
		sm_logger.logp( Level.SEVERE, sm_className, methodName, 
				"Invalid ODA data type: {0}", Integer.valueOf( odaDataType ) ); //$NON-NLS-1$
		throw new IllegalArgumentException( localizedMessage );
	}
	
       // for now, preserve existing behavior of mapping to an 
       // ODA IBlob and IClob classes
	if( odaDataType == Types.BLOB )
	  fieldClass = IBlob.class;
       else if( odaDataType == Types.CLOB )
	  fieldClass = IClob.class;
	
	if( sm_logger.isLoggable( Level.FINEST ) )
	    sm_logger.logp( Level.FINEST, sm_className, methodName, 
			"Converted from ODA data type {0} to Java data type class {1}.", 
			new Object[] { Integer.valueOf( odaDataType ), fieldClass } );
	
	return fieldClass;
}
 
Example 8
Source File: DataUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns oda type name
 * 
 * @param odaTypeCode
 * @return
 */
public static String getOdaTypeName( int odaTypeCode )
{
	switch ( odaTypeCode )
	{
		case Types.INTEGER :
			return "INT"; //$NON-NLS-1$
		case Types.DOUBLE :
		case Types.FLOAT :
			return "DOUBLE"; //$NON-NLS-1$
		case Types.VARCHAR :
			return "STRING"; //$NON-NLS-1$
		case Types.DATE :
			return "DATE"; //$NON-NLS-1$
		case Types.TIME :
			return "TIME"; //$NON-NLS-1$
		case Types.TIMESTAMP :
			return "TIMESTAMP"; //$NON-NLS-1$
		case Types.NUMERIC :
		case Types.DECIMAL :
			return "BIGDECIMAL"; //$NON-NLS-1$
		case Types.BLOB :
			return "BLOB"; //$NON-NLS-1$
		case Types.CLOB :
			return "CLOB"; //$NON-NLS-1$
		case Types.BOOLEAN :
			return "BOOLEAN"; //$NON-NLS-1$
		default :
			return "STRING"; //$NON-NLS-1$
	}
}
 
Example 9
Source File: RdbEventRecordLoader.java    From DataLink with Apache License 2.0 4 votes vote down vote up
@Override
protected void fillPreparedStatement(PreparedStatement ps, LobCreator lobCreator, RdbEventRecord record, DbDialect dbDialect, TaskWriterContext context) throws SQLException {
    EventType type = record.getEventType();
    // 注意insert/update语句对应的字段数序都是将主键排在后面
    List<EventColumn> columns = new ArrayList<EventColumn>();
    if (type.isInsert()) {
        columns.addAll(record.getColumns()); // insert为所有字段
        columns.addAll(record.getKeys());
    } else if (type.isDelete()) {
        columns.addAll(record.getKeys());
    } else if (type.isUpdate()) {
        boolean existOldKeys = !CollectionUtils.isEmpty(record.getOldKeys());
        boolean hasAutoIncrementNotKeyColumns = dbDialect.hasAutoIncrementNotKeyColumns(record.getSchemaName(), record.getTableName());
        if (hasAutoIncrementNotKeyColumns) {
            columns.addAll(record.getUpdatedColumns());// 只更新带有isUpdate=true的字段
        } else {
            columns.addAll(record.getColumns());// update、upsert都更新所有字段
        }
        columns.addAll(record.getKeys());
        if (existOldKeys) {
            columns.addAll(record.getOldKeys());
        }
    }

    // 获取一下当前字段名的数据是否必填
    boolean isSyncAutoAddColumn = context.getWriterParameter().isSyncAutoAddColumn();
    Map<String, Boolean> isRequiredMap = buildRequiredMap(dbDialect, record, columns, isSyncAutoAddColumn);
    Table table = dbDialect.findTable(record.getSchemaName(), record.getTableName());

    for (int i = 0; i < columns.size(); i++) {
        int paramIndex = i + 1;
        EventColumn column = columns.get(i);
        Boolean isRequired = isRequiredMap.get(StringUtils.lowerCase(column.getColumnName()));

        int sqlType = getSqlType(column, table, record);
        Object param = null;
        if (dbDialect instanceof MysqlDialect
                && (sqlType == Types.TIME || sqlType == Types.TIMESTAMP || sqlType == Types.DATE)) {
            // 解决mysql的0000-00-00 00:00:00问题,直接依赖mysql
            // driver进行处理,如果转化为Timestamp会出错
            param = column.getColumnValue();
        } else {
            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, param instanceof String ? ((String) param).getBytes() : (byte[]) param);
                    break;
                case Types.TIME:
                case Types.TIMESTAMP:
                case Types.DATE:
                    // 只处理mysql的时间类型,oracle的进行转化处理
                    if (dbDialect instanceof MysqlDialect) {
                        // 解决mysql的0000-00-00 00:00:00问题,直接依赖mysql
                        // driver进行处理,如果转化为Timestamp会出错
                        ps.setObject(paramIndex, param);
                    } else {
                        StatementCreatorUtils.setParameterValue(ps, paramIndex, sqlType, null, param);
                    }
                    break;
                case Types.BIT:
                    // 只处理mysql的bit类型,bit最多存储64位,所以需要使用BigInteger进行处理才能不丢精度
                    // mysql driver将bit按照setInt进行处理,会导致数据越界
                    if (dbDialect instanceof MysqlDialect) {
                        StatementCreatorUtils.setParameterValue(ps, paramIndex, Types.DECIMAL, null, param);
                    } else if (dbDialect instanceof SqlServerDialect) {
                        StatementCreatorUtils.setParameterValue(ps, paramIndex, sqlType, null, param.toString());
                    } else {
                        StatementCreatorUtils.setParameterValue(ps, paramIndex, sqlType, null, param);
                    }
                    break;
                default:
                    StatementCreatorUtils.setParameterValue(ps, paramIndex, sqlType, null, param);
                    break;
            }
        } catch (SQLException ex) {
            logger.error("SetParam error , [mappingId={}, sqltype={}, value={}]",
                    RecordMeta.mediaMapping(record).getId(), sqlType, param);
            throw ex;
        }
    }
}
 
Example 10
Source File: JDBCUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Get the SQLType for the given java.sql.Type type.
 *
 * @param type the java.sql.Type type specifier
 * @return SQLType.the SQLType for this java.sql.Type, or null if it's not recognized
 */
public static SQLType getSQLType(int type) {
    switch (type) {
        case Types.BIT: return SQLType.BIT;
        case Types.TINYINT: return SQLType.TINYINT;
        case Types.SMALLINT: return SQLType.SMALLINT;
        case Types.INTEGER: return SQLType.INTEGER;
        case Types.BIGINT: return SQLType.BIGINT;
        case Types.FLOAT: return SQLType.FLOAT;
        case Types.REAL: return SQLType.REAL;
        case Types.DOUBLE: return SQLType.DOUBLE;
        case Types.NUMERIC: return SQLType.NUMERIC;
        case Types.DECIMAL: return SQLType.DECIMAL;
        case Types.CHAR: return SQLType.CHAR;
        case Types.VARCHAR: return SQLType.VARCHAR;
        case Types.LONGVARCHAR: return SQLType.LONGVARCHAR;
        case Types.DATE: return SQLType.DATE;
        case Types.TIME: return SQLType.TIME;
        case Types.TIMESTAMP: return SQLType.TIMESTAMP;
        case Types.BINARY: return SQLType.BINARY;
        case Types.VARBINARY: return SQLType.VARBINARY;
        case Types.LONGVARBINARY: return SQLType.LONGVARBINARY;
        case Types.NULL: return SQLType.NULL;
        case Types.OTHER: return SQLType.OTHER;
        case Types.JAVA_OBJECT: return SQLType.JAVA_OBJECT;
        case Types.DISTINCT: return SQLType.DISTINCT;
        case Types.STRUCT: return SQLType.STRUCT;
        case Types.ARRAY: return SQLType.ARRAY;
        case Types.BLOB: return SQLType.BLOB;
        case Types.CLOB: return SQLType.CLOB;
        case Types.REF: return SQLType.REF;
        case Types.DATALINK: return SQLType.DATALINK;
        case Types.BOOLEAN: return SQLType.BOOLEAN;
        case Types.LONGNVARCHAR: return SQLType.LONGVARCHAR;
        case Types.NCHAR: return SQLType.CHAR;
        case Types.NCLOB: return SQLType.CLOB;
        case Types.NVARCHAR: return SQLType.VARCHAR;
        case Types.SQLXML: return SQLType.SQLXML;
        case Types.ROWID: return SQLType.ROWID;
        default:
            Logger.getLogger(JDBCUtils.class.getName()).log(Level.WARNING, "Unknown JDBC column type: " + type + ". Returns null.");
            return null;
    }
}
 
Example 11
Source File: DatabaseMetaDataTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Given a valid SQL type return the corresponding
 * JDBC type identifier from java.sql.Types.
 * Will assert if the type is not known
 * (in future, currently just return Types.NULL).
 */
public static int getJDBCType(String type)
{
    if ("SMALLINT".equals(type))
        return Types.SMALLINT;
    if ("INTEGER".equals(type) || "INT".equals(type))
        return Types.INTEGER;
    if ("BIGINT".equals(type))
        return Types.BIGINT;

    if (type.equals("FLOAT") || type.startsWith("FLOAT("))
        return Types.FLOAT;
    if (type.equals("REAL"))
        return Types.REAL;

    if ("DOUBLE".equals(type) || "DOUBLE PRECISION".equals(type))
        return Types.DOUBLE;

    if ("DATE".equals(type))
        return Types.DATE;
    if ("TIME".equals(type))
        return Types.TIME;
    if ("TIMESTAMP".equals(type))
        return Types.TIMESTAMP;

    if (type.equals("DECIMAL") || type.startsWith("DECIMAL("))
        return Types.DECIMAL;
    if (type.equals("NUMERIC") || type.startsWith("NUMERIC("))
        return Types.NUMERIC;

    if (type.endsWith("FOR BIT DATA")) {
       if (type.startsWith("CHAR"))
           return Types.BINARY;
       if (type.startsWith("CHARACTER"))
        return Types.BINARY;

       if (type.startsWith("VARCHAR"))
           return Types.VARBINARY;
       if (type.startsWith("CHARACTER VARYING"))
           return Types.VARBINARY;
       if (type.startsWith("CHAR VARYING"))
           return Types.VARBINARY;
    }

    if ("LONG VARCHAR".equals(type))
        return Types.LONGVARCHAR;
    if ("LONG VARCHAR FOR BIT DATA".equals(type))
        return Types.LONGVARBINARY;

    if (type.equals("CHAR") || type.startsWith("CHAR("))
        return Types.CHAR;
    if (type.equals("CHARACTER") ||
            type.startsWith("CHARACTER("))
        return Types.CHAR;

    if (type.equals("VARCHAR") || type.startsWith("VARCHAR("))
        return Types.VARCHAR;
    if (type.equals("CHARACTER VARYING") ||
            type.startsWith("CHARACTER VARYING("))
        return Types.VARCHAR;
    if (type.equals("CHAR VARYING") ||
            type.startsWith("CHAR VARYING("))
        return Types.VARCHAR;

    if (type.equals("BLOB") || type.startsWith("BLOB("))
        return Types.BLOB;
    if (type.equals("BINARY LARGE OBJECT") ||
            type.startsWith("BINARY LARGE OBJECT("))
        return Types.BLOB;

    if (type.equals("CLOB") || type.startsWith("CLOB("))
        return Types.CLOB;
    if (type.equals("CHARACTER LARGE OBJECT") ||
            type.startsWith("CHARACTER LARGE OBJECT("))
        return Types.CLOB;

    if ("XML".equals(type))
        return JDBC.SQLXML;

    fail("Unexpected SQL type: " + type);
    return Types.NULL;
}
 
Example 12
Source File: LengthOperatorNode.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Bind this operator
 *
 * @param fromList			The query's FROM list
 * @param subqueryList		The subquery list being built as we find SubqueryNodes
 * @param aggregateVector	The aggregate vector being built as we find AggregateNodes
 *
 * @return	The new top of the expression tree.
 *
 * @exception StandardException		Thrown on error
 */

public ValueNode bindExpression(
	FromList	fromList, SubqueryList subqueryList,
	Vector	aggregateVector)
		throws StandardException
{
	TypeId	operandType;

	bindOperand(fromList, subqueryList,
			aggregateVector);

	/*
	** Check the type of the operand - this function is allowed only on
	** string value types.  
	*/
	operandType = operand.getTypeId();
	switch (operandType.getJDBCTypeId())
	{
			case Types.CHAR:
			case Types.VARCHAR:
			case Types.BINARY:
			case Types.VARBINARY:
			case Types.LONGVARBINARY:
			case Types.LONGVARCHAR:
               case Types.BLOB:
               case Types.CLOB:
				break;
		
			default:
				throw StandardException.newException(SQLState.LANG_UNARY_FUNCTION_BAD_TYPE,
										getOperatorString(),
										operandType.getSQLTypeName());
	}

	/*
	** The result type of XXX_length is int.
	*/
	setType(new DataTypeDescriptor(
						TypeId.INTEGER_ID,
						operand.getTypeServices().isNullable()
					)
			);
	return this;
}
 
Example 13
Source File: MySqlBuilder.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void writeCastExpression(Column sourceColumn, Column targetColumn) throws IOException
{
    boolean sizeChanged = ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), sourceColumn, targetColumn);
    boolean typeChanged = ColumnDefinitionChange.isTypeChanged(getPlatformInfo(), sourceColumn, targetColumn);

    if (sizeChanged || typeChanged)
    {
        String targetNativeType = getNativeType(targetColumn);

        switch (targetColumn.getTypeCode())
        {
            case Types.BIT:
            case Types.BOOLEAN:
            case Types.TINYINT:
            case Types.SMALLINT:
            case Types.INTEGER:
            case Types.BIGINT:
                targetNativeType = "SIGNED";
                break;
            case Types.FLOAT:
            case Types.REAL:
            case Types.DOUBLE:
                targetNativeType = "SIGNED"; // ?
                break;
            case Types.DECIMAL:
            case Types.NUMERIC:
                targetNativeType = "DECIMAL";
                break;
            case Types.DATE:
                targetNativeType = "DATE";
                break;
            case Types.TIMESTAMP:
                targetNativeType = "DATETIME";
                break;
            case Types.CHAR:
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
            case Types.CLOB:
                targetNativeType = "CHAR";
                break;
            default:
                targetNativeType = "BINARY";
                break;
        }

        print("CAST(");
        if (TypeMap.isTextType(sourceColumn.getTypeCode()) && TypeMap.isTextType(targetColumn.getTypeCode()) && sizeChanged)
        {
            print("LEFT(");
            printIdentifier(getColumnName(sourceColumn));
            print(",");
            print(targetColumn.getSize());
            print(")");
        }
        else
        {
            printIdentifier(getColumnName(sourceColumn));
        }
        print(" AS ");
        print(getSqlType(targetColumn, targetNativeType));
        print(")");
    }
    else
    {
        printIdentifier(getColumnName(sourceColumn));
    }
}
 
Example 14
Source File: AvaticaSite.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
/** Similar logic to {@link #setObject}. */
public static Object get(Cursor.Accessor accessor, int targetSqlType,
    Calendar localCalendar) throws SQLException {
  switch (targetSqlType) {
  case Types.CLOB:
  case Types.DATALINK:
  case Types.NCLOB:
  case Types.REF:
  case Types.SQLXML:
    throw notImplemented();
  case Types.STRUCT:
    return accessor.getStruct();
  case Types.ARRAY:
    return accessor.getArray();
  case Types.BIGINT:
    final long aLong = accessor.getLong();
    if (aLong == 0 && accessor.wasNull()) {
      return null;
    }
    return aLong;
  case Types.BINARY:
  case Types.LONGVARBINARY:
  case Types.VARBINARY:
    return accessor.getBytes();
  case Types.BIT:
  case Types.BOOLEAN:
    final boolean aBoolean = accessor.getBoolean();
    if (!aBoolean && accessor.wasNull()) {
      return null;
    }
    return aBoolean;
  case Types.BLOB:
    return accessor.getBlob();
  case Types.DATE:
    return accessor.getDate(localCalendar);
  case Types.DECIMAL:
  case Types.NUMERIC:
    return accessor.getBigDecimal();
  case Types.DISTINCT:
    throw notImplemented();
  case Types.DOUBLE:
  case Types.FLOAT: // yes really; SQL FLOAT is up to 8 bytes
    final double aDouble = accessor.getDouble();
    if (aDouble == 0 && accessor.wasNull()) {
      return null;
    }
    return aDouble;
  case Types.INTEGER:
    final int anInt = accessor.getInt();
    if (anInt == 0 && accessor.wasNull()) {
      return null;
    }
    return anInt;
  case Types.JAVA_OBJECT:
  case Types.OTHER:
    return accessor.getObject();
  case Types.LONGNVARCHAR:
  case Types.LONGVARCHAR:
  case Types.NVARCHAR:
  case Types.VARCHAR:
  case Types.CHAR:
  case Types.NCHAR:
    return accessor.getString();
  case Types.REAL:
    final float aFloat = accessor.getFloat();
    if (aFloat == 0 && accessor.wasNull()) {
      return null;
    }
    return aFloat;
  case Types.ROWID:
    throw notImplemented();
  case Types.SMALLINT:
    final short aShort = accessor.getShort();
    if (aShort == 0 && accessor.wasNull()) {
      return null;
    }
    return aShort;
  case Types.TIME:
    return accessor.getTime(localCalendar);
  case Types.TIMESTAMP:
    return accessor.getTimestamp(localCalendar);
  case Types.TINYINT:
    final byte aByte = accessor.getByte();
    if (aByte == 0 && accessor.wasNull()) {
      return null;
    }
    return aByte;
  default:
    throw notImplemented();
  }
}
 
Example 15
Source File: MTypesTranslator.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public TClass typeClassForJDBCType(int jdbcType,
                                   String schemaName, String tableName, String columnName) {
    switch (jdbcType) {
    case Types.BIGINT:
        return MNumeric.BIGINT;
    case Types.BINARY:
    case Types.BIT:
        return MBinary.BINARY;
    case Types.CHAR:
    case Types.NCHAR:
        return MString.CHAR;
    case Types.CLOB:
    case Types.NCLOB:
    case Types.LONGVARCHAR:
    case Types.LONGNVARCHAR:
  //case Types.SQLXML:
        return MString.LONGTEXT;
    case Types.DATE:
        return MDateAndTime.DATE;
    case Types.DECIMAL:
    case Types.NUMERIC:
        return MNumeric.DECIMAL;
    case Types.DOUBLE:
        return MApproximateNumber.DOUBLE;
    case Types.FLOAT:
    case Types.REAL:
        return MApproximateNumber.FLOAT;
    case Types.INTEGER:
        return MNumeric.INT;
    case Types.SMALLINT:
        return MNumeric.SMALLINT;
    case Types.TIME:
        return MDateAndTime.TIME;
    case Types.TIMESTAMP:
        return MDateAndTime.DATETIME; // (Not TIMESTAMP.)
    case Types.TINYINT:
        return MNumeric.TINYINT;
    case Types.VARBINARY:
        return MBinary.VARBINARY;
    case Types.VARCHAR:
    case Types.NVARCHAR:
        return MString.VARCHAR;
    default:
        return super.typeClassForJDBCType(jdbcType, schemaName, tableName, columnName);
    }
}
 
Example 16
Source File: DBPersistenceManager.java    From mobile-persistence with MIT License 4 votes vote down vote up
/**
 * Returns a set of rows by applying the searchValue to applicable columns in the table.
 * The where clause is constructed by looping over all direct or one-to-one attribute mappings, checking whether
 * the mapping attribute is of the proper type (String or number when the searchValue is a numeric value), and in the list
 * of attrNames (when specified), and if so, the column is added to the where clause. If the column is of a string type, 
 * the LIKE opertaor is used and the searchValue is suffixed with the wildcard character "%". 
 * If the column is numeric, the = operator is used.
 * 
 * @param entityClass
 * @param searchValue
 * @param attrNamesToSearch list of attribute names to search on. If empty or null, all attributes with matching type 
 * will be searched on
 * @return List of matching entity instances
 */
public <E extends Entity> List<E> find(Class entityClass, String searchValue, List<String> attrNamesToSearch)
{
  ObjectPersistenceMapping persMapping = ObjectPersistenceMapping.getInstance();
  ClassMappingDescriptor descriptor = persMapping.findClassMappingDescriptor(entityClass.getName());
  StringBuffer sql = getSqlSelectFromPart(descriptor);

  List<BindParamInfo> bindParamInfos = new ArrayList<BindParamInfo>();
  List<AttributeMappingDirect> attributeMappings = descriptor.getAttributeMappingsDirect();
  BigDecimal numericSearchValue = getBigDecimalValue(searchValue);
  boolean isNumeric = numericSearchValue!=null;
  for (AttributeMappingDirect mapping : attributeMappings)
  {
    if (attrNamesToSearch!=null && !attrNamesToSearch.contains(mapping.getAttributeName()))
    {
      // skip this attr
      continue;
    }
    BindParamInfo bindParamInfo = constructBindParamInfo(entityClass, mapping);
    // check the SQL type to determine whether we can search on it, and the operator
    int sqlType = bindParamInfo.getSqlType();
    if (sqlType==Types.CHAR || sqlType==Types.CLOB || sqlType==Types.VARCHAR)
    {
      bindParamInfo.setValue(searchValue.toUpperCase()+"%");
      bindParamInfo.setOperator(SQL_LIKE_OPERATOR);
      bindParamInfo.setCaseInsensitive(true);
      bindParamInfos.add(bindParamInfo);            
    }
    else if (isNumeric
            && (sqlType==Types.BIGINT ||sqlType==Types.DECIMAL || sqlType==Types.DOUBLE || sqlType==Types.FLOAT
                || sqlType==Types.INTEGER || sqlType==Types.NUMERIC || sqlType==Types.SMALLINT) )
    {
      bindParamInfo.setValue(numericSearchValue);
      // no need to set operator, default operator is already "="
      bindParamInfos.add(bindParamInfo);              
    }
  }    
  sql = constructWhereClause(sql, bindParamInfos, SQL_OR_OPERATOR);
  sql = constructOrderByClause(sql, descriptor);
  ResultSet set = executeSqlSelect(sql.toString(), bindParamInfos);
  return createEntitiesFromResultSet(set, descriptor.getAttributeMappings());
}
 
Example 17
Source File: PrestoResultSetMetaData.java    From presto with Apache License 2.0 4 votes vote down vote up
@Override
public String getColumnClassName(int column)
        throws SQLException
{
    // see javax.sql.rowset.RowSetMetaDataImpl
    switch (column(column).getColumnType()) {
        case Types.NUMERIC:
        case Types.DECIMAL:
            return BigDecimal.class.getName();
        case Types.BOOLEAN:
        case Types.BIT:
            return Boolean.class.getName();
        case Types.TINYINT:
            return Byte.class.getName();
        case Types.SMALLINT:
            return Short.class.getName();
        case Types.INTEGER:
            return Integer.class.getName();
        case Types.BIGINT:
            return Long.class.getName();
        case Types.REAL:
            return Float.class.getName();
        case Types.FLOAT:
        case Types.DOUBLE:
            return Double.class.getName();
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            return "byte[]";
        case Types.DATE:
            return Date.class.getName();
        case Types.TIME:
            return Time.class.getName();
        case Types.TIMESTAMP:
            return Timestamp.class.getName();
        case Types.BLOB:
            return Blob.class.getName();
        case Types.CLOB:
            return Clob.class.getName();
        case Types.ARRAY:
            return Array.class.getName();
    }
    return String.class.getName();
}
 
Example 18
Source File: ConnManager.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 4 votes vote down vote up
/**
 * Resolve a database-specific type to the Java type that should contain it.
 * @param sqlType     sql type
 * @return the name of a Java type to hold the sql datatype, or null if none.
 */
public String toJavaType(int sqlType) {
  // Mappings taken from:
  // http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
  if (sqlType == Types.INTEGER) {
    return "Integer";
  } else if (sqlType == Types.VARCHAR) {
    return "String";
  } else if (sqlType == Types.CHAR) {
    return "String";
  } else if (sqlType == Types.LONGVARCHAR) {
    return "String";
  } else if (sqlType == Types.NVARCHAR) {
    return "String";
  } else if (sqlType == Types.NCHAR) {
    return "String";
  } else if (sqlType == Types.LONGNVARCHAR) {
    return "String";
  } else if (sqlType == Types.NUMERIC) {
    return "java.math.BigDecimal";
  } else if (sqlType == Types.DECIMAL) {
    return "java.math.BigDecimal";
  } else if (sqlType == Types.BIT) {
    return "Boolean";
  } else if (sqlType == Types.BOOLEAN) {
    return "Boolean";
  } else if (sqlType == Types.TINYINT) {
    return "Integer";
  } else if (sqlType == Types.SMALLINT) {
    return "Integer";
  } else if (sqlType == Types.BIGINT) {
    return "Long";
  } else if (sqlType == Types.REAL) {
    return "Float";
  } else if (sqlType == Types.FLOAT) {
    return "Double";
  } else if (sqlType == Types.DOUBLE) {
    return "Double";
  } else if (sqlType == Types.DATE) {
    return "java.sql.Date";
  } else if (sqlType == Types.TIME) {
    return "java.sql.Time";
  } else if (sqlType == Types.TIMESTAMP) {
    return "java.sql.Timestamp";
  } else if (sqlType == Types.BINARY
      || sqlType == Types.VARBINARY) {
    return BytesWritable.class.getName();
  } else if (sqlType == Types.CLOB) {
    return ClobRef.class.getName();
  } else if (sqlType == Types.BLOB
      || sqlType == Types.LONGVARBINARY) {
    return BlobRef.class.getName();
  } else {
    // TODO(aaron): Support DISTINCT, ARRAY, STRUCT, REF, JAVA_OBJECT.
    // Return null indicating database-specific manager should return a
    // java data type if it can find one for any nonstandard type.
    return null;
  }
}
 
Example 19
Source File: DataTypeDescriptor.java    From Oceanus with Apache License 2.0 2 votes vote down vote up
/**
 * Determine if an ASCII stream can be inserted into a column or parameter
 * of type <code>jdbcType</code>.
 *
 * @param jdbcType JDBC type of column or parameter
 * @return <code>true</code> if an ASCII stream can be inserted;
 *               <code>false</code> otherwise
 */
public static boolean isAsciiStreamAssignable(int jdbcType) {
    return jdbcType == Types.CLOB || isCharacterType(jdbcType);
}