List of usage examples for java.sql ResultSetMetaData getColumnTypeName
String getColumnTypeName(int column) throws SQLException;
From source file:com.waveerp.DbInformation.java
public String loadDataEntries() { // Added by Jammi Dee 05/03/2012 registrySystem rss = new registrySystem(); url = rss.readRegistry("NA", "NA", "NA", "DBURL"); dbName = rss.readRegistry("NA", "NA", "NA", "DBDATABASE"); driver = rss.readRegistry("NA", "NA", "NA", "DBDRIVER"); user = rss.readRegistry("NA", "NA", "NA", "DBUSER"); password = rss.readRegistry("NA", "NA", "NA", "DBPASSWORD"); // Override Wave ERP database dbName = "information_schema"; // Added by Jammi Dee 05/03/2012 // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); try {// www .j a va 2 s. com Class.forName(getDriver()); con = DriverManager.getConnection(url + dbName, user, password); ps = con.createStatement(); ps1 = con.createStatement(); rs = ps.executeQuery(querystring); rs1 = ps1.executeQuery( "select column_name, concat( column_name,':','[', data_type, column_key ,']' ), table_name from columns where table_schema = 'DBWAVEERP';"); ///////////////////////////////////////////// // Get the number of columns here. I need // this to add dynaminism to my table loader ///////////////////////////////////////////// ResultSetMetaData rsmd = rs.getMetaData(); setColCount(rsmd.getColumnCount()); /////////////////////////////////////////// // Load the column types to an array // Never access it directly, java simply // returns NULL, whew I don't know why /////////////////////////////////////////// String[] colTypes = new String[colCount]; for (int j = 0; j <= getColCount() - 1; j++) { colTypes[j] = rsmd.getColumnTypeName(j + 1); } /** * Initialize the working arrays here for the process * Added by Jammi Dee 06/06/2012 */ while (rs.next()) { String id = rs.getString(1); } rs.last(); int rowCount = rs.getRow(); while (rs1.next()) { String id = rs1.getString(1); } rs1.last(); int rowCount1 = rs1.getRow(); rowCount = rowCount + rowCount1; nodeid = new String[rowCount]; nodedesc = new String[rowCount]; nodeparent = new String[rowCount]; int ipoint = 0; rs.beforeFirst(); rs1.beforeFirst(); while (rs.next()) { nodeid[ipoint] = rs.getString(1); nodedesc[ipoint] = rs.getString(2); nodeparent[ipoint] = rs.getString(3); // Increment the pointer ipoint = ipoint + 1; } while (rs1.next()) { nodeid[ipoint] = rs1.getString(1); nodedesc[ipoint] = rs1.getString(2); nodeparent[ipoint] = rs1.getString(3); // Increment the pointer ipoint = ipoint + 1; } ps.close(); con.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); return "FAILED"; } return "SUCCESS"; }
From source file:com.xpfriend.fixture.cast.temp.Database.java
private DynaClass getDynaClass(ResultSet resultSet) throws SQLException { ResultSetMetaData md = resultSet.getMetaData(); int count = md.getColumnCount(); DynaProperty[] properties = new DynaProperty[count]; for (int i = 0; i < properties.length; i++) { int column = i + 1; Class<?> type = TypeConverter.getJavaType(md.getColumnType(column), md.getColumnTypeName(column), md.getPrecision(column), md.getScale(column)); String name = getColumnLabel(md, column); properties[i] = new DynaProperty(name, type); }//from w ww. j a v a 2 s. c o m return new BasicDynaClass(null, null, properties); }
From source file:org.apache.hadoop.hive.jdbc.storagehandler.AtsdDBRecordReader.java
private ResultSet replaceDotsInColumnNames(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); if (columnCount > 0) { CachedRowSetImpl crs = new CachedRowSetImpl(); crs.populate(resultSet);// w w w . j a v a 2 s.c o m RowSetMetaDataImpl rwsm = new RowSetMetaDataImpl(); rwsm.setColumnCount(columnCount); for (int i = 1; i <= columnCount; i++) { String columnName = metaData.getColumnName(i); if (columnName.contains(".")) { columnName = columnName.replaceAll("\\.", "\\$"); } rwsm.setColumnName(i, columnName); rwsm.setColumnLabel(i, metaData.getColumnLabel(i)); rwsm.setCatalogName(i, metaData.getCatalogName(i)); rwsm.setColumnType(i, metaData.getColumnType(i)); rwsm.setColumnTypeName(i, metaData.getColumnTypeName(i)); rwsm.setSchemaName(i, metaData.getSchemaName(i)); rwsm.setTableName(i, metaData.getTableName(i)); } crs.setMetaData(rwsm); return crs; } return resultSet; }
From source file:org.apache.sqoop.manager.SqlManager.java
protected Map<String, String> getColumnTypeNamesForRawQuery(String stmt) { ResultSet results;/*www.jav a2s.com*/ try { results = execute(stmt); } catch (SQLException sqlE) { LOG.error("Error executing statement: " + sqlE.toString(), sqlE); release(); return null; } try { Map<String, String> colTypeNames = new HashMap<String, String>(); int cols = results.getMetaData().getColumnCount(); ResultSetMetaData metadata = results.getMetaData(); for (int i = 1; i < cols + 1; i++) { String colTypeName = metadata.getColumnTypeName(i); String colName = metadata.getColumnName(i); if (colName == null || colName.equals("")) { colName = metadata.getColumnLabel(i); } colTypeNames.put(colName, colTypeName); } return colTypeNames; } catch (SQLException sqlException) { LOG.error("Error reading from database: " + sqlException.toString()); return null; } finally { try { results.close(); getConnection().commit(); } catch (SQLException sqlE) { LOG.warn("SQLException closing ResultSet: " + sqlE.toString()); } release(); } }
From source file:org.apache.kylin.query.adhoc.PushDownRunnerJdbcImpl.java
@Override public void executeQuery(String query, List<List<String>> results, List<SelectedColumnMeta> columnMetas) throws Exception { Statement statement = null;/*from w w w . j av a 2 s. c om*/ Connection connection = this.getConnection(); ResultSet resultSet = null; //extract column metadata ResultSetMetaData metaData = null; int columnCount = 0; try { statement = connection.createStatement(); resultSet = statement.executeQuery(query); extractResults(resultSet, results); metaData = resultSet.getMetaData(); 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), false, metaData.isCurrency(i), metaData.isNullable(i), false, metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i), null, null, null, metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i), false, false)); } } catch (SQLException sqlException) { throw sqlException; } finally { DBUtils.closeQuietly(resultSet); DBUtils.closeQuietly(statement); closeConnection(connection); } }
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 w ww . j a v a2s.c o m*/ 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.fastcatsearch.datasource.reader.DBReader.java
@Override public void init() throws IRException { isClosed = false;/*from w w w.ja v a2 s. c o m*/ BULK_SIZE = getConfigInt("bulkSize"); useBlobFile = getConfigBoolean("useBlobFile"); tmpFile = new ArrayList<File>(); dataSet = new Map[BULK_SIZE]; String jdbcSourceId = getConfigString("jdbcSourceId"); JDBCSourceInfo jdbcSourceInfo = null; IRService irService = ServiceManager.getInstance().getService(IRService.class); List<JDBCSourceInfo> jdbcSourceInfoList = irService.getJDBCSourceConfig().getJdbcSourceInfoList(); for (JDBCSourceInfo info : jdbcSourceInfoList) { if (info.getId().equals(jdbcSourceId)) { jdbcSourceInfo = info; break; } } try { con = getConnection(jdbcSourceInfo); doBeforeQuery(); String deleteIdSQL = getConfigString("deleteIdSQL"); if (deleteIdSQL != null && deleteIdSQL.length() > 0) { PreparedStatement idPstmt = null; ResultSet rs = null; ResultSetMetaData rm = null; try { idPstmt = con.prepareStatement(q(deleteIdSQL)); rs = idPstmt.executeQuery(); rm = rs.getMetaData(); while (rs.next()) { String[] rid = new String[rm.getColumnCount()]; for (int inx = 0; inx < rid.length; inx++) { rid[inx] = rs.getString(inx + 1); } deleteIdList.add(rid); } } finally { if (idPstmt != null) { try { idPstmt.close(); } catch (Exception e) { } } if (rs != null) { try { rs.close(); } catch (Exception e) { } } } } String dataSQL = getConfigString("dataSQL"); if (dataSQL == null || dataSQL.length() == 0) { throw new IRException("Data query sql is empty!"); } if (logger.isTraceEnabled()) { logger.trace("real query = {}", q(dataSQL)); } else { logger.debug("Data query = {}", dataSQL); } int fetchSize = getConfigInt("fetchSize"); if (fetchSize < 0) { //in mysql, fetch data row by row pstmt = con.prepareStatement(q(dataSQL), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); pstmt.setFetchSize(Integer.MIN_VALUE); } else { pstmt = con.prepareStatement(q(dataSQL)); if (fetchSize > 0) { pstmt.setFetchSize(fetchSize); } } if (maxRows > 0) { pstmt.setMaxRows(maxRows); } r = pstmt.executeQuery(); ResultSetMetaData rsMetadata = r.getMetaData(); columnCount = rsMetadata.getColumnCount(); columnName = new String[columnCount]; for (int i = 0; i < columnCount; i++) { columnName[i] = rsMetadata.getColumnLabel(i + 1).toUpperCase(); String typeName = rsMetadata.getColumnTypeName(i + 1); logger.info("Column-{} [{}]:[{}]", new Object[] { i + 1, columnName[i], typeName }); } } catch (Exception e) { closeConnection(); throw new IRException(e); } }
From source file:com.tesora.dve.sql.util.JdbcConnectionResourceResponse.java
private void assertEqualProxyConnMetadata(String cntxt, ProxyConnectionResourceResponse pcrr) throws Throwable { ResultSetMetaData rsmd = results.getMetaData(); ColumnSet sysColumns = pcrr.getColumns(); assertEquals(cntxt + " mismatched column set width", rsmd.getColumnCount(), sysColumns.getColumnList().size()); List<ColumnMetadata> sysCols = sysColumns.getColumnList(); for (int i = 0; i < rsmd.getColumnCount(); i++) { ColumnMetadata sc = sysCols.get(i); String colcntxt = cntxt + " column " + sc.getAliasName(); // still don't handle non column labels right assertEquals(colcntxt + " mismatched column name", rsmd.getColumnName(i + 1), sc.getName()); assertEquals(colcntxt + " mismatched column label", rsmd.getColumnLabel(i + 1), sc.getAliasName()); if (rsmd.getColumnType(i + 1) != sc.getDataType()) { // emit names - easier to read fail(colcntxt + " mismatched column type. Expected " + rsmd.getColumnTypeName(i + 1) + " (" + rsmd.getColumnType(i + 1) + ") but found " + sc.getTypeName() + " (" + sc.getDataType() + ")"); }/*from w w w.j a v a2s .c o m*/ } }
From source file:com.chiorichan.database.DatabaseEngine.java
public static Map<String, Object> convertRow(ResultSet rs) throws SQLException { Map<String, Object> result = Maps.newLinkedHashMap(); ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); for (int i = 1; i < numColumns + 1; i++) { String columnName = rsmd.getColumnName(i); // Loader.getLogger().info( "Column: " + columnName + " <-> " + rsmd.getColumnTypeName( i ) ); if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { result.put(columnName, rs.getArray(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) // Sometimes tinyints are read as bits {/*from www . j a v a 2s. c om*/ result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { result.put(columnName, rs.getBoolean(columnName)); } else if (rsmd.getColumnTypeName(i).contains("BLOB") || rsmd.getColumnType(i) == java.sql.Types.BINARY) { // BLOG = Max Length 65,535. Recommended that you use a LONGBLOG. byte[] bytes = rs.getBytes(columnName); result.put(columnName, bytes); /* * try * { * result.put( columnName, new String( bytes, "ISO-8859-1" ) ); * } * catch ( UnsupportedEncodingException e ) * { * e.printStackTrace(); * } */ } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { result.put(columnName, rs.getDouble(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { result.put(columnName, rs.getFloat(columnName)); } else if (rsmd.getColumnTypeName(i).equals("INT")) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { result.put(columnName, rs.getNString(columnName)); } else if (rsmd.getColumnTypeName(i).equals("VARCHAR")) { result.put(columnName, rs.getString(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { result.put(columnName, rs.getInt(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { result.put(columnName, rs.getDate(columnName)); } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { result.put(columnName, rs.getTimestamp(columnName)); } else { result.put(columnName, rs.getObject(columnName)); } } return result; }
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 w w w .ja v a 2 s. 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); } }