Java Code Examples for java.sql.ResultSetMetaData#getColumnType()

The following examples show how to use java.sql.ResultSetMetaData#getColumnType() . 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: SQLBrokerQueryFactory.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public String resultSetToString(ResultSet resultSet) throws SQLException {
  ResultSetMetaData metaData = resultSet.getMetaData();
  int numColumns = metaData.getColumnCount();
  StringBuffer sb = new StringBuffer("");
  int rowNum = 0;
  while (resultSet.next() == true) {
    sb.append("Row " + rowNum++ + " : ");
    for (int i = 0; i < numColumns; i++) {
      String columnName = metaData.getColumnName(i);
      int type = metaData.getColumnType(i);
      sb.append(columnName);
      sb.append("=");
      sb.append(resultSet.getObject(i).toString());
      if (i < numColumns - 1) {
        sb.append(",");
      }
    }
  }
  return sb.toString();
}
 
Example 2
Source File: PreparedStatementTest.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
boolean isEqualsTo(ResultSetMetaData metadata, int colNum) throws SQLException {
  return
      metadata.getCatalogName(colNum).equals(InfoSchemaConstants.IS_CATALOG_NAME) &&
      metadata.getSchemaName(colNum).isEmpty() &&
      metadata.getTableName(colNum).isEmpty() &&
      metadata.getColumnName(colNum).equals(columnName) &&
      metadata.getColumnLabel(colNum).equals(columnName) &&
      metadata.getColumnType(colNum) == type &&
      metadata.isNullable(colNum) == nullable &&
      // There is an existing bug where query results doesn't contain the precision for VARCHAR field.
      //metadata.getPrecision(colNum) == precision &&
      metadata.getScale(colNum) == scale &&
      metadata.isSigned(colNum) == signed &&
      metadata.getColumnDisplaySize(colNum) == displaySize &&
      metadata.getColumnClassName(colNum).equals(className) &&
      metadata.isSearchable(colNum) &&
      metadata.isAutoIncrement(colNum) == false &&
      metadata.isCaseSensitive(colNum) == false &&
      metadata.isReadOnly(colNum) &&
      metadata.isWritable(colNum) == false &&
      metadata.isDefinitelyWritable(colNum) == false &&
      metadata.isCurrency(colNum) == false;
}
 
Example 3
Source File: SQLBrokerQueryFactory.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public String resultSetToString(ResultSet resultSet) throws SQLException {
  ResultSetMetaData metaData = resultSet.getMetaData();
  int numColumns = metaData.getColumnCount();
  StringBuffer sb = new StringBuffer("");
  int rowNum = 0;
  while (resultSet.next() == true) {
    sb.append("Row " + rowNum++ + " : ");
    for (int i = 0; i < numColumns; i++) {
      String columnName = metaData.getColumnName(i);
      int type = metaData.getColumnType(i);
      sb.append(columnName);
      sb.append("=");
      sb.append(resultSet.getObject(i).toString());
      if (i < numColumns - 1) {
        sb.append(",");
      }
    }
  }
  return sb.toString();
}
 
Example 4
Source File: SingleTableSplitUtil.java    From DataLink with Apache License 2.0 6 votes vote down vote up
private static boolean isPKTypeValid(ResultSetMetaData rsMetaData) {
    boolean ret = false;
    try {
        int minType = rsMetaData.getColumnType(1);
        int maxType = rsMetaData.getColumnType(2);

        boolean isNumberType = isLongType(minType);

        boolean isStringType = isStringType(minType);

        if (minType == maxType && (isNumberType || isStringType)) {
            ret = true;
        }
    } catch (Exception e) {
        throw DataXException.asDataXException(DBUtilErrorCode.ILLEGAL_SPLIT_PK,
                "DataX获取切分主键(splitPk)字段类型失败. 该错误通常是系统底层异常导致. 请联系旺旺:askdatax或者DBA处理.");
    }
    return ret;
}
 
Example 5
Source File: QueryHeaderBuilder.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
private static QueryHeader build(final ResultSetMetaData resultSetMetaData, final SchemaContext schema, final String columnName, final int columnIndex) throws SQLException {
    String schemaName = schema.getName();
    String actualTableName = resultSetMetaData.getTableName(columnIndex);
    Optional<DataNodeRoutedRule> dataNodeRoutedRule = schema.getSchema().getRules().stream().filter(each -> each instanceof DataNodeRoutedRule).findFirst().map(rule -> (DataNodeRoutedRule) rule);
    String tableName;
    boolean primaryKey;
    if (null != actualTableName && dataNodeRoutedRule.isPresent()) {
        tableName = dataNodeRoutedRule.get().findLogicTableByActualTable(actualTableName).orElse("");
        TableMetaData tableMetaData = schema.getSchema().getMetaData().getSchema().getConfiguredSchemaMetaData().get(tableName);
        primaryKey = null != tableMetaData && tableMetaData.getColumns().get(columnName.toLowerCase()).isPrimaryKey();
    } else {
        tableName = actualTableName;
        primaryKey = false;
    }
    String columnLabel = resultSetMetaData.getColumnLabel(columnIndex);
    int columnLength = resultSetMetaData.getColumnDisplaySize(columnIndex);
    Integer columnType = resultSetMetaData.getColumnType(columnIndex);
    int decimals = resultSetMetaData.getScale(columnIndex);
    boolean signed = resultSetMetaData.isSigned(columnIndex);
    boolean notNull = resultSetMetaData.isNullable(columnIndex) == ResultSetMetaData.columnNoNulls;
    boolean autoIncrement = resultSetMetaData.isAutoIncrement(columnIndex);
    return new QueryHeader(schemaName, tableName, columnLabel, columnName, columnLength, columnType, decimals, signed, primaryKey, notNull, autoIncrement);
}
 
Example 6
Source File: DbConn.java    From jqm with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> runSelectSingleRow(String query_key, Object... params)
{
    HashMap<String, Object> res = new HashMap<>();
    try (ResultSet rs = runSelect(query_key, params))
    {
        if (!rs.next())
        {
            throw new NoResultException("The query returned zero rows when one was expected.");
        }
        ResultSetMetaData meta = rs.getMetaData();
        for (int i = 1; i <= meta.getColumnCount(); i++)
        {
            // We take the type as returned, with an exception for small numerics (we do not want long or BigInt which cannot be cast)
            Object or;
            if (meta.getColumnType(i) == java.sql.Types.NUMERIC && meta.getPrecision(i) <= 10)
            {
                or = rs.getInt(i);
            }
            else
            {
                or = rs.getObject(i);
            }
            res.put(meta.getColumnName(i).toUpperCase(), or);
        }

        if (rs.next())
        {
            throw new NonUniqueResultException("The query returned more than one row when one was expected");
        }
    }
    catch (SQLException e)
    {
        throw new DatabaseException(e);
    }
    return res;
}
 
Example 7
Source File: AbstractDatabaseFetchProcessor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public void setup(final ProcessContext context) {
    final String maxValueColumnNames = context.getProperty(MAX_VALUE_COLUMN_NAMES).evaluateAttributeExpressions().getValue();

    // If there are no max-value column names specified, we don't need to perform this processing
    if (StringUtils.isEmpty(maxValueColumnNames)) {
        return;
    }

    // Try to fill the columnTypeMap with the types of the desired max-value columns
    final DBCPService dbcpService = context.getProperty(DBCP_SERVICE).asControllerService(DBCPService.class);
    final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions().getValue();

    final DatabaseAdapter dbAdapter = dbAdapters.get(context.getProperty(DB_TYPE).getValue());
    try (final Connection con = dbcpService.getConnection();
         final Statement st = con.createStatement()) {

        // Try a query that returns no rows, for the purposes of getting metadata about the columns. It is possible
        // to use DatabaseMetaData.getColumns(), but not all drivers support this, notably the schema-on-read
        // approach as in Apache Drill
        String query = dbAdapter.getSelectStatement(tableName, maxValueColumnNames, "1 = 0", null, null, null);
        ResultSet resultSet = st.executeQuery(query);
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        int numCols = resultSetMetaData.getColumnCount();
        if (numCols > 0) {
            columnTypeMap.clear();
            for (int i = 1; i <= numCols; i++) {
                String colName = resultSetMetaData.getColumnName(i).toLowerCase();
                String colKey = getStateKey(tableName, colName);
                int colType = resultSetMetaData.getColumnType(i);
                columnTypeMap.putIfAbsent(colKey, colType);
            }
        } else {
            throw new ProcessException("No columns found in table from those specified: " + maxValueColumnNames);
        }

    } catch (SQLException e) {
        throw new ProcessException("Unable to communicate with database in order to determine column types", e);
    }
}
 
Example 8
Source File: SURQueryMixTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Updates the current row in the ResultSet using updateRow()
 * @param rs ResultSet to be updated
 * @param meta meta for the ResultSet
 **/
private void updatePositioned(final ResultSet rs, 
                              final ResultSetMetaData meta) 
    throws SQLException                          
{
    StringBuffer sb = new StringBuffer();
    sb.append("UPDATE T1 SET ");
    for (int column = 1; column<=meta.getColumnCount(); column++) {
        sb.append(meta.getColumnName(column));
        sb.append("=?");
        if (column<meta.getColumnCount()) {
            sb.append(",");
        }
    }
    sb.append(" WHERE CURRENT OF \"");
    sb.append(cursorName);
    sb.append("\"");
    println(sb.toString());
    PreparedStatement ps = prepareStatement(sb.toString());
    
    for (int column = 1; column<=meta.getColumnCount(); column++) {
       if (meta.getColumnType(column)==Types.INTEGER) {
            // Set to negative value
            ps.setInt(column, -rs.getInt(column));
        } else {
            ps.setString(column, "UPDATED_" + rs.getString(column));
        }
    }
    assertEquals("Expected one row to be updated", 1, ps.executeUpdate());        
}
 
Example 9
Source File: MSSQLConnection.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected List<Integer> getGeometryColumns(final ResultSetMetaData rsmd) throws SQLException {
	final int numberOfColumns = rsmd.getColumnCount();
	final List<Integer> geoColumn = new ArrayList<>();
	for (int i = 1; i <= numberOfColumns; i++) {
		if (vender.equalsIgnoreCase(MSSQL) && rsmd.getColumnType(i) == 2004) {
			geoColumn.add(i);
		}
	}
	return geoColumn;

}
 
Example 10
Source File: CsharpGivenSqlResultSetExtractor.java    From dal with Apache License 2.0 5 votes vote down vote up
@Override
public List<AbstractParameterHost> extract(ResultSet rs) throws SQLException {
    List<AbstractParameterHost> hosts = new ArrayList<>();
    if (rs == null) {
        return hosts;
    }

    ResultSetMetaData metaData = rs.getMetaData();
    int count = metaData.getColumnCount();
    for (int i = 1; i <= count; i++) {
        CSharpParameterHost host = new CSharpParameterHost();
        String columnName = metaData.getColumnLabel(i);
        host.setName(columnName);
        String typeName = metaData.getColumnTypeName(i);
        boolean isUnsigned = DbUtils.isColumnUnsigned(typeName);
        int dataType = metaData.getColumnType(i);
        int length = metaData.getColumnDisplaySize(i);
        // 特殊处理
        DbType dbType = DbUtils.getDotNetDbType(typeName, dataType, length, isUnsigned, dbCategory);
        host.setDbType(dbType);
        String type = DbType.getCSharpType(host.getDbType());
        host.setType(type);
        host.setIdentity(false);
        host.setNullable(metaData.isNullable(i) == 1 ? true : false);
        host.setPrimary(false);
        host.setLength(length);
        host.setValueType(Consts.CSharpValueTypes.contains(host.getType()));
        hosts.add(host);
    }

    return hosts;
}
 
Example 11
Source File: Type1BlobResourcesConversionHandler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Object getSource(String id, ResultSet rs) throws SQLException
{
	ResultSetMetaData metadata = rs.getMetaData();
	String rv = null;
	switch(metadata.getColumnType(1))
	{
	case Types.BLOB:
		Blob blob = rs.getBlob(1);
		if(blob != null)
		{
			rv = new String(blob.getBytes(1L, (int) blob.length()));
		}
		break;
	case Types.CLOB:
		Clob clob = rs.getClob(1);
		if(clob != null)
		{
			rv = clob.getSubString(1L, (int) clob.length());
		}
		break;
	case Types.CHAR:
	case Types.LONGVARCHAR:
	case Types.VARCHAR:
	case Types.BINARY:
	case Types.VARBINARY:
	case Types.LONGVARBINARY:
		byte[] bytes = rs.getBytes(1);
		if(bytes != null)
		{
			rv = new String(bytes);
		}
		break;
	}
	return rv;
}
 
Example 12
Source File: JDBCAvroRegistryString.java    From components with Apache License 2.0 5 votes vote down vote up
protected Schema inferSchemaResultSetMetaData(ResultSetMetaData metadata) throws SQLException {
    List<Field> fields = new ArrayList<>();

    Set<String> existNames = new HashSet<String>();
    int index = 0;
    
    int count = metadata.getColumnCount();
    for (int i = 1; i <= count; i++) {
        int size = metadata.getPrecision(i);
        int scale = metadata.getScale(i);
        boolean nullable = ResultSetMetaData.columnNullable == metadata.isNullable(i);

        int dbtype = metadata.getColumnType(i);
        String fieldName = metadata.getColumnLabel(i);
        String dbColumnName = metadata.getColumnName(i);

        // not necessary for the result schema from the query statement
        boolean isKey = false;

        String validName = NameUtil.correct(fieldName, index++, existNames);
        existNames.add(validName);
        
        Field field = sqlType2Avro(size, scale, dbtype, nullable, validName, dbColumnName, null, isKey);

        fields.add(field);
    }
    return Schema.createRecord("DYNAMIC", null, null, false, fields);
}
 
Example 13
Source File: SURQueryMixTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the current row in the ResultSet using updateRow()
 * @param rs ResultSet to be updated
 * @param meta meta for the ResultSet
 **/
private void updatePositioned(final ResultSet rs, 
                              final ResultSetMetaData meta) 
    throws SQLException                          
{
    StringBuilder sb = new StringBuilder();
    sb.append("UPDATE T1 SET ");
    for (int column = 1; column<=meta.getColumnCount(); column++) {
        sb.append(meta.getColumnName(column));
        sb.append("=?");
        if (column<meta.getColumnCount()) {
            sb.append(",");
        }
    }
    sb.append(" WHERE CURRENT OF \"");
    sb.append(cursorName);
    sb.append("\"");
    println(sb.toString());
    PreparedStatement ps = prepareStatement(sb.toString());
    
    for (int column = 1; column<=meta.getColumnCount(); column++) {
       if (meta.getColumnType(column)==Types.INTEGER) {
            // Set to negative value
            ps.setInt(column, -rs.getInt(column));
        } else {
            ps.setString(column, "UPDATED_" + rs.getString(column));
        }
    }
    assertEquals("Expected one row to be updated", 1, ps.executeUpdate());        
}
 
Example 14
Source File: OffsetFetchNextTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Positive tests, result set metadata
 */
public void testMetadata() throws Exception
{
    Statement stm = createStatement();
    ResultSet   rs;
    String[]    variants;

    variants = makeVariants( "select * from t1%", NEXT_ROWS_ONLY, "1", null );
    for ( int j = 0; j < variants.length; j++ )
    {
        rs = stm.executeQuery( variants[ j ] );
        ResultSetMetaData rsmd= rs.getMetaData();
        int cnt = rsmd.getColumnCount();

        String[] cols = new String[]{"A","B"};
        int[] types = {Types.INTEGER, Types.BIGINT};

        for (int i=1; i <= cnt; i++) {
            String name = rsmd.getColumnName(i);
            int type = rsmd.getColumnType(i);

            assertTrue(name.equals(cols[i-1]));
            assertTrue(type == types[i-1]);
        }

        rs.close();
    }
    
    stm.close();
}
 
Example 15
Source File: MetaDataRegressionTest.java    From r-course with MIT License 5 votes vote down vote up
/**
 * Tests fix for BUG#3570 -- inconsistent reporting of column type
 * 
 * @throws Exception
 *             if an error occurs
 */
public void testBug3570() throws Exception {
    String createTableQuery = " CREATE TABLE testBug3570(field_tinyint TINYINT,field_smallint SMALLINT,field_mediumint MEDIUMINT"
            + ",field_int INT,field_integer INTEGER,field_bigint BIGINT,field_real REAL,field_float FLOAT,field_decimal DECIMAL"
            + ",field_numeric NUMERIC,field_double DOUBLE,field_char CHAR(3),field_varchar VARCHAR(255),field_date DATE"
            + ",field_time TIME,field_year YEAR,field_timestamp TIMESTAMP,field_datetime DATETIME,field_tinyblob TINYBLOB"
            + ",field_blob BLOB,field_mediumblob MEDIUMBLOB,field_longblob LONGBLOB,field_tinytext TINYTEXT,field_text TEXT"
            + ",field_mediumtext MEDIUMTEXT,field_longtext LONGTEXT,field_enum ENUM('1','2','3'),field_set SET('1','2','3'))";

    try {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3570");
        this.stmt.executeUpdate(createTableQuery);

        ResultSet dbmdRs = this.conn.getMetaData().getColumns(this.conn.getCatalog(), null, "testBug3570", "%");

        this.rs = this.stmt.executeQuery("SELECT * FROM testBug3570");

        ResultSetMetaData rsmd = this.rs.getMetaData();

        while (dbmdRs.next()) {
            String columnName = dbmdRs.getString(4);
            int typeFromGetColumns = dbmdRs.getInt(5);
            int typeFromRSMD = rsmd.getColumnType(this.rs.findColumn(columnName));

            //
            // TODO: Server needs to send these types correctly....
            //
            if (!"field_tinyblob".equals(columnName) && !"field_tinytext".equals(columnName)) {
                assertTrue(columnName + " -> type from DBMD.getColumns(" + typeFromGetColumns + ") != type from RSMD.getColumnType(" + typeFromRSMD + ")",
                        typeFromGetColumns == typeFromRSMD);
            }
        }
    } finally {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3570");
    }
}
 
Example 16
Source File: JDBCDataSource.java    From ontopia with Apache License 2.0 5 votes vote down vote up
private TupleReader(Relation relation) {
  // build sql statement from relation definition
  StringBuilder sb = new StringBuilder();
  sb.append("select r.");
  String[] rcols = relation.getColumns();
  sb.append(StringUtils.join(rcols, ", r."));
  sb.append(" from ");
  sb.append(relation.getName());
  sb.append(" r");

  // add condtion if specified
  String condition = relation.getCondition();
  if (condition != null) {
    sb.append(" where ");
    sb.append(condition);
  }

  String sql = sb.toString();
  log.debug("tuple query: {}", sql);

  // prepare query
  Connection conn = getConnection();
  try {
    stm = conn.prepareStatement(sql);
    stm.setFetchSize(1000);
    rs = stm.executeQuery();

    // get column datatypes
    coltypes = new int[rcols.length];
    ResultSetMetaData md = rs.getMetaData();
    for (int i=0; i < coltypes.length; i++) {
      coltypes[i] = md.getColumnType(i+1);
    }

  } catch (SQLException e) {
    throw new OntopiaRuntimeException("Error in query: " + sql, e);
  }
  
}
 
Example 17
Source File: KamiQuery.java    From kamike.divide with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void fillResultTypes(ResultSet rs) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();

    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
        int type = rsmd.getColumnType(i);
        String name = rsmd.getColumnName(i);
        switch (type) {
            case Types.BIGINT:
                types.add(GenericType.Long);
                break;
            case Types.BIT:
            case Types.BOOLEAN:
            case Types.INTEGER:
            case Types.TINYINT:
            case Types.SMALLINT:
                types.add(GenericType.Int);
                break;
            case Types.CHAR:
            case Types.CLOB:
            case Types.LONGNVARCHAR:
            case Types.LONGVARCHAR:
            case Types.NCHAR:
            case Types.NCLOB:
            case Types.VARCHAR:
                types.add(GenericType.String);
                break;
            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP:
                types.add(GenericType.Timestamp);
                break;
            case Types.DECIMAL:
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.NUMERIC:
                types.add(GenericType.Double);
            default:
                types.add(GenericType.String);
                break;
        }

    }

}
 
Example 18
Source File: XDataFrameFactory.java    From morpheus-core with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <R> DataFrame<R,String> from(ResultSet resultSet, int rowCapacity, Function<ResultSet, R> rowKeyFunction) throws SQLException {
    try {
        if (!resultSet.next()) {
            return createFrame(Index.empty(), resultSet);
        } else {
            final R rowKey = rowKeyFunction.apply(resultSet);
            final Index<R> rowIndex = Index.of((Class<R>)rowKey.getClass(), rowCapacity);
            final DataFrame<R,String> frame = createFrame(rowIndex, resultSet);
            final ResultSetMetaData metaData = resultSet.getMetaData();
            final int columnCount = metaData.getColumnCount();
            while (resultSet.next()) {
                final R key = rowKeyFunction.apply(resultSet);
                frame.rows().add(key);
                final int rowOrdinal = frame.rowCount()-1;
                for (int i=1; i<=columnCount; ++i) {
                    final int colOrdinal = i-1;
                    switch (metaData.getColumnType(i)) {
                        case Types.BIT:         frame.data().setBoolean(rowOrdinal, colOrdinal, resultSet.getBoolean(i));  break;
                        case Types.NVARCHAR:    frame.data().setValue(rowOrdinal, colOrdinal, resultSet.getString(i));     break;
                        case Types.CLOB:        frame.data().setValue(rowOrdinal, colOrdinal, resultSet.getString(i));     break;
                        case Types.VARCHAR:     frame.data().setValue(rowOrdinal, colOrdinal, resultSet.getString(i));     break;
                        case Types.BOOLEAN:     frame.data().setBoolean(rowOrdinal, colOrdinal, resultSet.getBoolean(i));  break;
                        case Types.DECIMAL:     frame.data().setDouble(rowOrdinal, colOrdinal, resultSet.getDouble(i));    break;
                        case Types.DATE:        frame.data().setValue(rowOrdinal, colOrdinal, resultSet.getDate(i));       break;
                        case Types.FLOAT:       frame.data().setDouble(rowOrdinal, colOrdinal, resultSet.getFloat(i));     break;
                        case Types.INTEGER:     frame.data().setInt(rowOrdinal, colOrdinal, resultSet.getInt(i));          break;
                        case Types.TINYINT:     frame.data().setInt(rowOrdinal, colOrdinal, resultSet.getShort(i));        break;
                        case Types.SMALLINT:    frame.data().setInt(rowOrdinal, colOrdinal, resultSet.getInt(i));          break;
                        case Types.BIGINT:      frame.data().setLong(rowOrdinal, colOrdinal, resultSet.getLong(i));        break;
                        case Types.TIMESTAMP:   frame.data().setValue(rowOrdinal, colOrdinal, resultSet.getTimestamp(i));  break;
                        case Types.DOUBLE:      frame.data().setDouble(rowOrdinal, colOrdinal, resultSet.getDouble(i));    break;
                        case Types.NUMERIC:     frame.data().setDouble(rowOrdinal, colOrdinal, resultSet.getDouble(i));    break;
                        case Types.CHAR:        frame.data().setValue(rowOrdinal, colOrdinal, resultSet.getString(i));     break;
                        default:                frame.data().setValue(rowOrdinal, colOrdinal, resultSet.getObject(i));     break;
                    }
                }
            }
            return frame;
        }
    } catch (Throwable t) {
        throw new DataFrameException("Failed to initialize DataFrame from ResultSet: " + t.getMessage(), t);
    }
}
 
Example 19
Source File: ResultColumnList.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/** 
 * Generate an RCL to match the contents of a ResultSetMetaData.
 * This is useful when dealing with VTIs.
 *
 * @param rsmd			The ResultSetMetaData.
 * @param tableName		The TableName for the BCNs.
 * @param javaClassName	The name of the VTI
 *
 * @exception StandardException			Thrown on error
 */
public void createListFromResultSetMetaData(ResultSetMetaData rsmd,
											TableName tableName,
											String javaClassName)
		throws StandardException
{
	try
	{
		// JDBC columns #s are 1-based
		// Check to make sure # of columns >= 1
		int numColumns = rsmd.getColumnCount();

		if (numColumns <= 0)
		{
			throw StandardException.newException(SQLState.LANG_INVALID_V_T_I_COLUMN_COUNT, 
								javaClassName, String.valueOf(numColumns));
		}

		for (int index = 1; index <= numColumns; index++)
		{
			boolean nullableResult = 
				(rsmd.isNullable(index) != ResultSetMetaData.columnNoNulls);

			TypeId cti;

			int jdbcColumnType = rsmd.getColumnType(index);

			switch (jdbcColumnType) {
			case Types.JAVA_OBJECT:
			case Types.OTHER:
			{
				cti = TypeId.getUserDefinedTypeId(rsmd.getColumnTypeName(index), false);
				break;
			}
			default:
			{
				cti = TypeId.getBuiltInTypeId(jdbcColumnType);
				break;
			}
			}

			// Handle the case where a VTI returns a bad column type
			if (cti == null)
			{
				throw StandardException.newException(SQLState.LANG_BAD_J_D_B_C_TYPE_INFO, Integer.toString(index));
			}

			// Get the maximum byte storage for this column
			int maxWidth;

			/* Get maximum byte storage from rsmd for variable
			 * width types, set it to MAXINT for the long types,
			 * otherwise get it from the TypeId
			 */
			if (cti.variableLength())
			{
				maxWidth = rsmd.getColumnDisplaySize(index);
			}
			else if (jdbcColumnType == Types.LONGVARCHAR ||
					 jdbcColumnType == Types.LONGVARBINARY)
			{
				maxWidth = Integer.MAX_VALUE;
			}
			else
			{
				maxWidth = 0;
			}

			int precision = cti.isDecimalTypeId() ? rsmd.getPrecision(index) : 0;
			int scale = cti.isDecimalTypeId() ? rsmd.getScale(index) : 0;
			DataTypeDescriptor dts = new DataTypeDescriptor(cti, 
										precision,
										scale, 
										nullableResult, 
										maxWidth);
			addColumn( tableName, rsmd.getColumnName(index), dts );
		}
	}
	catch (Throwable t)
	{
		if (t instanceof StandardException)
		{
			throw (StandardException) t;
		}
		else
		{
			throw StandardException.unexpectedUserException(t);
		}
	}
}
 
Example 20
Source File: EventCallbackListener.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Build the query string to insert a row to the backend database
 * 
 * @param event
 *          the callback event
 * @return SQL query string to insert a row to the back-end database
 * @throws SQLException
 */
private String buildInsertQuery(Event event) throws SQLException {

  ResultSetMetaData meta = event.getResultSetMetaData();

  List<Object> newRow = event.getNewRow();

  StringBuilder query = new StringBuilder();

  // insert into table_name values (...); assume
  // Note: insert into table_name(col1, col2 ...) values (...) is not
  // supported here
  //query.append("INSERT INTO " + meta.getSchemaName(1) + "."
  //    + meta.getTableName(1) + " VALUES (");
  query.append("INSERT INTO " + meta.getSchemaName(1) + "." + meta.getTableName(1) + "_ONE VALUES (");

  for (int i = 1; i <= meta.getColumnCount(); i++) {

    int type = meta.getColumnType(i);

    Object value = newRow.get(i - 1);

    switch (type) {
    case Types.BIGINT:
    case Types.DECIMAL:
    case Types.NUMERIC:
    case Types.SMALLINT:
    case Types.TINYINT:
    case Types.INTEGER:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.REAL:
    case Types.TIMESTAMP:
      query.append(value + ",");
      break;
    default:
      query.append("'" + value + "',");
    }
  }

  query.delete(query.length() - 1, query.length());

  query.append(");");

  return query.toString();

}