List of usage examples for java.sql ResultSetMetaData getPrecision
int getPrecision(int column) throws SQLException;
From source file:com.mapd.utility.SQLImporter.java
private void createMapDTable(ResultSetMetaData metaData) { StringBuilder sb = new StringBuilder(); sb.append("Create table ").append(cmd.getOptionValue("targetTable")).append("("); // Now iterate the metadata try {//from w w w .java 2s . c om for (int i = 1; i <= metaData.getColumnCount(); i++) { if (i > 1) { sb.append(","); } LOGGER.debug("Column name is " + metaData.getColumnName(i)); LOGGER.debug("Column type is " + metaData.getColumnTypeName(i)); LOGGER.debug("Column type is " + metaData.getColumnType(i)); sb.append(metaData.getColumnName(i)).append(" "); sb.append(getColType(metaData.getColumnType(i), metaData.getPrecision(i), metaData.getScale(i))); } sb.append(")"); if (Integer.valueOf(cmd.getOptionValue("fragmentSize", "0")) > 0) { sb.append(" with (fragment_size = "); sb.append(cmd.getOptionValue("fragmentSize", "0")); sb.append(")"); } } catch (SQLException ex) { LOGGER.error("Error processing the metadata - " + ex.toString()); exit(1); } executeMapDCommand(sb.toString()); }
From source file:org.seasar.dbflute.logic.jdbc.metadata.synonym.DfSynonymExtractorOracle.java
protected List<DfColumnMeta> getSynonymColumns(Connection conn, UnifiedSchema synonymOwner, String synonymName) throws SQLException { final List<DfColumnMeta> columnList = new ArrayList<DfColumnMeta>(); Statement st = null;//from ww w . ja v a2 s . com ResultSet rs = null; try { st = conn.createStatement(); final String synonymSqlName = synonymOwner.buildSchemaQualifiedName(synonymName); final String sql = "select * from " + synonymSqlName + " where 0=1"; rs = st.executeQuery(sql); final ResultSetMetaData metaData = rs.getMetaData(); int count = metaData.getColumnCount(); for (int i = 0; i < count; i++) { int index = i + 1; String columnName = metaData.getColumnName(index); int columnType = metaData.getColumnType(index); String columnTypeName = metaData.getColumnTypeName(index); int precision = metaData.getPrecision(index); int scale = metaData.getScale(index); int nullableType = metaData.isNullable(index); DfColumnMeta column = new DfColumnMeta(); column.setColumnName(columnName); column.setJdbcDefValue(columnType); column.setDbTypeName(columnTypeName); column.setColumnSize(precision); column.setDecimalDigits(scale); column.setRequired(nullableType == ResultSetMetaData.columnNoNulls); columnList.add(column); } return columnList; } finally { if (st != null) { try { st.close(); } catch (SQLException ignored) { } } if (rs != null) { try { rs.close(); } catch (SQLException ignored) { } } } }
From source file:org.apache.sqoop.connector.hbase.HbaseFromInitializer.java
@Override public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig, FromJobConfiguration fromJobConfig) { executor = new HbaseExecutor(linkConfig.linkConfig); String schemaName = fromJobConfig.fromJobConfig.tableName; if (schemaName == null) { schemaName = "Query"; } else if (fromJobConfig.fromJobConfig.schemaName != null) { schemaName = fromJobConfig.fromJobConfig.schemaName + "." + schemaName; }//from w w w . j a va 2 s .c o m Schema schema = new Schema(schemaName); ResultSet rs = null; ResultSetMetaData rsmt = null; try { rs = executor.executeQuery(context.getString(HbaseConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL) .replace(HbaseConnectorConstants.SQL_CONDITIONS_TOKEN, "1 = 0")); rsmt = rs.getMetaData(); for (int i = 1; i <= rsmt.getColumnCount(); i++) { String columnName = rsmt.getColumnLabel(i); if (StringUtils.isEmpty(columnName)) { columnName = rsmt.getColumnName(i); if (StringUtils.isEmpty(columnName)) { columnName = "Column " + i; } } Column column = SqlTypesUtils.sqlTypeToSchemaType(rsmt.getColumnType(i), columnName, rsmt.getPrecision(i), rsmt.getScale(i)); schema.addColumn(column); } return schema; } catch (SQLException e) { throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0016, e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.info("Ignoring exception while closing ResultSet", e); } } if (executor != null) { executor.close(); } } }
From source file:ro.nextreports.designer.dbviewer.DefaultDBViewer.java
public List<DBColumn> getColumns(String schema, String table) throws NextSqlException, MalformedTableNameException { Connection con;//from w w w . j av a2 s . c o m List<DBColumn> columns = new ArrayList<DBColumn>(); String schemaName; String escapedTableName; try { con = Globals.getConnection(); if (schema == null) { schemaName = Globals.getConnection().getMetaData().getUserName(); } else { schemaName = schema; } Dialect dialect = Globals.getDialect(); if (dialect.isKeyWord(table)) { escapedTableName = dialect.getEscapedKeyWord(table); } else { escapedTableName = table; } } catch (Exception e) { throw new NextSqlException("Could not retrieve connection.", e); } ResultSet rs = null; Statement stmt = null; List<String> keyColumns = new ArrayList<String>(); try { // primary keys DatabaseMetaData dbmd = con.getMetaData(); rs = dbmd.getPrimaryKeys(null, schemaName, table); while (rs.next()) { keyColumns.add(rs.getString("COLUMN_NAME")); } closeResultSet(rs); // foreign keys rs = dbmd.getImportedKeys(null, schemaName, table); List<String> foreignColumns = new ArrayList<String>(); HashMap<String, DBForeignColumnInfo> fkMap = new HashMap<String, DBForeignColumnInfo>(); while (rs.next()) { String fkSchema = rs.getString("FKTABLE_SCHEM"); String fkTable = rs.getString("FKTABLE_NAME"); String fkColumn = rs.getString("FKCOLUMN_NAME"); String pkSchema = rs.getString("PKTABLE_SCHEM"); String pkTable = rs.getString("PKTABLE_NAME"); String pkColumn = rs.getString("PKCOLUMN_NAME"); DBForeignColumnInfo fkInfo = new DBForeignColumnInfo(fkSchema, fkTable, fkColumn, pkSchema, pkTable, pkColumn); //System.out.println("fkInfo : " + fkInfo); foreignColumns.add(fkColumn); fkMap.put(fkColumn, fkInfo); } closeResultSet(rs); // column names with index rs = dbmd.getIndexInfo(null, schemaName, table, false, true); List<String> indexes = new ArrayList<String>(); while (rs.next()) { String indexName = rs.getString(9); if (indexName != null) { indexes.add(indexName); } } closeResultSet(rs); DataSource ds = DefaultDataSourceManager.getInstance().getConnectedDataSource(); String header = ""; stmt = con.createStatement(); try { // workaround if a table name contains spaces if (escapedTableName.indexOf(" ") != -1) { escapedTableName = "\"" + escapedTableName + "\""; } String prefix = ""; if (!NO_SCHEMA_NAME.equals(schemaName)) { prefix = schemaName; } if (prefix.indexOf(" ") != -1) { prefix = "\"" + prefix + "\""; } if (!"".equals(prefix)) { prefix = prefix + "."; } if (ds.getDriver().equals(CSVDialect.DRIVER_CLASS)) { header = (String) ds.getProperties().get("headerline"); if (header == null) { header = ""; } } if (header.isEmpty()) { String s = "SELECT * FROM " + prefix + escapedTableName + " WHERE 1 = 0"; LOG.info("getColumns[ " + s + "]"); rs = stmt.executeQuery(s); } } catch (SQLException e) { e.printStackTrace(); throw new MalformedTableNameException(e); } if (header.isEmpty()) { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int col = 1; col <= columnCount; col++) { String name = rsmd.getColumnLabel(col); int length = rsmd.getColumnDisplaySize(col); int precision = rsmd.getPrecision(col); int scale = rsmd.getScale(col); boolean isPrimaryKey = false; boolean isForeignKey = false; boolean isIndex = false; if (keyColumns.contains(name)) { isPrimaryKey = true; } DBForeignColumnInfo fkInfo = null; if (foreignColumns.contains(name)) { isForeignKey = true; fkInfo = fkMap.get(name); } if (indexes.contains(name)) { isIndex = true; } DBColumn column = new DBColumn(schemaName, table, name, rsmd.getColumnTypeName(col), isPrimaryKey, isForeignKey, isIndex, fkInfo, length, precision, scale); columns.add(column); } } else { String columnTypes = (String) ds.getProperties().get("columnTypes"); String[] names = header.split(","); String[] types = new String[names.length]; for (int i = 0; i < types.length; i++) { types[i] = "String"; } if ((columnTypes != null) && !columnTypes.isEmpty()) { types = columnTypes.split(","); } for (int i = 0; i < names.length; i++) { DBColumn column = new DBColumn(schemaName, table, names[i], types[i], false, false, false, null, 20, 0, 0); columns.add(column); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); e.printStackTrace(); throw new NextSqlException("SQL Exception: " + e.getMessage(), e); } finally { closeResultSet(rs); closeStatement(stmt); } return columns; }
From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java
private void checkPrecision(int expected, String sql) throws SQLException { ResultSetMetaData meta = stat.executeQuery(sql).getMetaData(); assertEquals(expected, meta.getPrecision(1)); }
From source file:com.kylinolap.rest.service.QueryService.java
/** * @param sql/*from www .j ava 2 s . c o m*/ * @param project * @return * @throws Exception */ private SQLResponse execute(String sql, SQLRequest sqlRequest) throws Exception { Connection conn = null; Statement stat = null; ResultSet resultSet = null; List<List<String>> results = new LinkedList<List<String>>(); List<SelectedColumnMeta> columnMetas = new LinkedList<SelectedColumnMeta>(); try { conn = getOLAPDataSource(sqlRequest.getProject()).getConnection(); if (sqlRequest instanceof PrepareSqlRequest) { PreparedStatement preparedState = conn.prepareStatement(sql); for (int i = 0; i < ((PrepareSqlRequest) sqlRequest).getParams().length; i++) { setParam(preparedState, i + 1, ((PrepareSqlRequest) sqlRequest).getParams()[i]); } resultSet = preparedState.executeQuery(); } else { stat = conn.createStatement(); resultSet = stat.executeQuery(sql); } ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); // Fill in selected column meta for (int i = 1; i <= columnCount; ++i) { columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i), metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i), metaData.isSigned(i), metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i), metaData.getSchemaName(i), metaData.getCatalogName(i), metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i), metaData.isWritable(i), metaData.isDefinitelyWritable(i))); } List<String> oneRow = new LinkedList<String>(); // fill in results while (resultSet.next()) { for (int i = 0; i < columnCount; i++) { oneRow.add((resultSet.getString(i + 1))); } results.add(new LinkedList<String>(oneRow)); oneRow.clear(); } } catch (Exception e) { logger.error(e.getLocalizedMessage(), e); throw e; } finally { close(resultSet, stat, conn); } boolean isPartialResult = false; String cube = ""; long totalScanCount = 0; for (OLAPContext ctx : OLAPContext.getThreadLocalContexts()) { isPartialResult |= ctx.storageContext.isPartialResultReturned(); cube = ctx.cubeInstance.getName(); totalScanCount += ctx.storageContext.getTotalScanCount(); } SQLResponse response = new SQLResponse(columnMetas, results, cube, 0, false, null, isPartialResult); response.setTotalScanCount(totalScanCount); return response; }
From source file:mondrian.spi.impl.JdbcDialectImpl.java
void logTypeInfo(ResultSetMetaData metaData, int columnIndex, SqlStatement.Type internalType) throws SQLException { if (LOGGER.isDebugEnabled()) { final int columnType = metaData.getColumnType(columnIndex + 1); final int precision = metaData.getPrecision(columnIndex + 1); final int scale = metaData.getScale(columnIndex + 1); final String columnName = metaData.getColumnName(columnIndex + 1); LOGGER.debug("JdbcDialectImpl.getType " + "Dialect- " + this.getDatabaseProduct() + ", Column-" + columnName + " is of internal type " + internalType + ". JDBC type was " + columnType + ". Column precision=" + precision + ". Column scale=" + scale); }// w w w . j av a 2 s . c o m }
From source file:kenh.xscript.database.beans.ResultSetBean.java
/** * Use result set to initial a bean.//w ww . j a v a 2 s. c om * * @param rs * @param includeFieldName * @throws SQLException * @throws IllegalAccessException * @throws InstantiationException */ public ResultSetBean(ResultSet rs, boolean includeFieldName) throws SQLException, IllegalAccessException, InstantiationException { include_field_name = includeFieldName; LazyDynaClass beanClass = new LazyDynaClass(); ResultSetMetaData m = rs.getMetaData(); for (int i = 1; i <= m.getColumnCount(); i++) { Column c = new Column(); try { c.catalogName = m.getCatalogName(i); } catch (SQLException e) { } try { c.className = m.getColumnClassName(i); } catch (SQLException e) { } try { c.displaySize = m.getColumnDisplaySize(i); } catch (SQLException e) { } try { c.label = m.getColumnLabel(i); } catch (SQLException e) { } try { c.name = m.getColumnName(i); } catch (SQLException e) { } try { c.type = m.getColumnType(i); } catch (SQLException e) { } try { c.typeName = m.getColumnTypeName(i); } catch (SQLException e) { } try { c.precision = m.getPrecision(i); } catch (SQLException e) { } try { c.scale = m.getScale(i); } catch (SQLException e) { } try { c.schemaName = m.getSchemaName(i); } catch (SQLException e) { } try { c.tableName = m.getTableName(i); } catch (SQLException e) { } beanClass.add(m.getColumnLabel(i).toLowerCase()); beanClass.add("" + i); cols.add(c); } DynaBean colBean = beanClass.newInstance(); int i = 1; for (Column col : cols) { String field = col.getLabel().toLowerCase(); colBean.set(field, col.getLabel()); colBean.set("" + i, col.getLabel()); i++; } if (include_field_name) rows.add(colBean); while (rs.next()) { DynaBean bean = beanClass.newInstance(); i = 1; for (Column c : cols) { String field = c.getLabel().toLowerCase(); Object obj = rs.getObject(field); bean.set(field, obj); bean.set("" + i, obj); i++; } rows.add(bean); } }
From source file:mondrian.spi.impl.JdbcDialectImpl.java
public SqlStatement.Type getType(ResultSetMetaData metaData, int columnIndex) throws SQLException { final int columnType = metaData.getColumnType(columnIndex + 1); SqlStatement.Type internalType = null; if (columnType != Types.NUMERIC && columnType != Types.DECIMAL) { internalType = DEFAULT_TYPE_MAP.get(columnType); } else {//from w w w.j a v a2 s . c om final int precision = metaData.getPrecision(columnIndex + 1); final int scale = metaData.getScale(columnIndex + 1); if (scale == 0 && precision <= 9) { // An int (up to 2^31 = 2.1B) can hold any NUMBER(10, 0) value // (up to 10^9 = 1B). internalType = SqlStatement.Type.INT; } else { internalType = SqlStatement.Type.DOUBLE; } } internalType = internalType == null ? SqlStatement.Type.OBJECT : internalType; logTypeInfo(metaData, columnIndex, internalType); return internalType; }
From source file:com.streamsets.pipeline.stage.processor.parser.sql.SqlParserProcessor.java
private void resolveSchema(SchemaAndTable schemaAndTable) throws StageException { Map<String, Integer> columns = new HashMap<>(); String schema = schemaAndTable.getSchema(); String table = schemaAndTable.getTable(); try (Statement s = connection.createStatement()) { ResultSetMetaData md = s .executeQuery(Utils.format("SELECT * FROM {}{} WHERE 1 = 0", StringUtils.isNotEmpty(schema) ? "\"" + schema + "\"." : "", "\"" + table + "\"")) .getMetaData();/*from ww w .ja v a 2s .c o m*/ int colCount = md.getColumnCount(); for (int i = 1; i <= colCount; i++) { int colType = md.getColumnType(i); String colName = md.getColumnName(i); if (!configBean.caseSensitive) { colName = colName.toUpperCase(); } if (colType == Types.DATE || colType == Types.TIME || colType == Types.TIMESTAMP) { dateTimeColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>()); dateTimeColumns.get(schemaAndTable).put(colName, md.getColumnTypeName(i)); } if (colType == Types.DECIMAL || colType == Types.NUMERIC) { decimalColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>()).put(colName, new PrecisionAndScale(md.getPrecision(i), md.getScale(i))); } columns.put(md.getColumnName(i), md.getColumnType(i)); } tableSchemas.put(schemaAndTable, columns); } catch (SQLException ex) { throw new StageException(JDBC_00, configBean.hikariConfigBean.connectionString); } }