List of usage examples for java.sql ResultSetMetaData isAutoIncrement
boolean isAutoIncrement(int column) throws SQLException;
From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java
/** * Constructs a new ColumnMetaData objects from given ResultSetMetaData with provided column default values map and * the object's index./*from w ww .j a v a 2 s . c o m*/ * * @param rsmd * A ResultSetMetaData which contains meta information about all columns for the table. * @param columnDefaultValues * A map of possibly defined values by default for columns. * @param i * Index of column which should be constructed. * @return A constructed ColumnMetaData object. * @throws SQLException * Is thrown in case any errors during work with database occur. */ private ColumnMetaData getColumnMetaData(ResultSetMetaData rsmd, Map<String, String> columnDefaultValues, int i) throws SQLException { SqlTypes columnType = SqlTypes.getSqlTypeByJdbcSqlType(rsmd.getColumnType(i)); ColumnMetaData column = ColumnMetaData.getInstance(rsmd.getColumnName(i), columnType) .setNullable(rsmd.isNullable(i) == ResultSetMetaData.columnNullable) .setAutoincrement(rsmd.isAutoIncrement(i)); if (columnDefaultValues.containsKey(rsmd.getColumnName(i))) { column.setDefaultValue(columnDefaultValues.get(rsmd.getColumnName(i))); } if (columnType.isHasSize()) { column.setSize(rsmd.getColumnDisplaySize(i)); } return column; }
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 .jav a 2s . c o m*/ 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:com.kylinolap.rest.service.QueryService.java
/** * @param sql/* www. ja v a 2s. c om*/ * @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:com.xpfriend.fixture.cast.temp.Database.java
private boolean hasIdentityColumnInternal(String tableName) { DbCommand command = createCommand("select * from " + tableName); try {/* w w w . j ava 2 s . co m*/ ResultSet resultSet = command.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { if (metaData.isAutoIncrement(i)) { return true; } } return false; } catch (SQLException e) { throw new ConfigException(e); } finally { command.close(); } }
From source file:org.apache.kylin.rest.service.QueryService.java
/** * @param correctedSql/*www .j av a 2 s. co m*/ * @param sqlRequest * @return * @throws Exception */ private SQLResponse execute(String correctedSql, SQLRequest sqlRequest) throws Exception { Connection conn = null; Statement stat = null; ResultSet resultSet = null; Boolean isPushDown = false; List<List<String>> results = Lists.newArrayList(); List<SelectedColumnMeta> columnMetas = Lists.newArrayList(); try { conn = cacheService.getOLAPDataSource(sqlRequest.getProject()).getConnection(); // special case for prepare query. if (BackdoorToggles.getPrepareOnly()) { return getPrepareOnlySqlResponse(correctedSql, conn, isPushDown, results, columnMetas); } stat = conn.createStatement(); processStatementAttr(stat, sqlRequest); resultSet = stat.executeQuery(correctedSql); 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))); } // fill in results while (resultSet.next()) { List<String> oneRow = Lists.newArrayListWithCapacity(columnCount); for (int i = 0; i < columnCount; i++) { oneRow.add((resultSet.getString(i + 1))); } results.add(oneRow); } } catch (SQLException sqlException) { isPushDown = PushDownUtil.doPushDownQuery(sqlRequest.getProject(), correctedSql, results, columnMetas, sqlException); } finally { close(resultSet, stat, conn); } return getSqlResponse(isPushDown, results, columnMetas); }
From source file:org.apache.ddlutils.platform.JdbcModelReader.java
/** * Helper method that determines the auto increment status for the given columns via the * {@link ResultSetMetaData#isAutoIncrement(int)} method. * /* ww w . ja v a 2s . co m*/ * @param table The table * @param columnsToCheck The columns to check (e.g. the primary key columns) */ protected void determineAutoIncrementFromResultSetMetaData(Table table, Column[] columnsToCheck) throws SQLException { if ((columnsToCheck == null) || (columnsToCheck.length == 0)) { return; } StringBuffer query = new StringBuffer(); query.append("SELECT "); for (int idx = 0; idx < columnsToCheck.length; idx++) { if (idx > 0) { query.append(","); } if (getPlatform().isDelimitedIdentifierModeOn()) { query.append(getPlatformInfo().getDelimiterToken()); } //==> FIX query.append(table.getName()).append('.'); //<== FIX query.append(columnsToCheck[idx].getName()); if (getPlatform().isDelimitedIdentifierModeOn()) { query.append(getPlatformInfo().getDelimiterToken()); } } query.append(" FROM "); if (getPlatform().isDelimitedIdentifierModeOn()) { query.append(getPlatformInfo().getDelimiterToken()); } query.append(table.getName()); if (getPlatform().isDelimitedIdentifierModeOn()) { query.append(getPlatformInfo().getDelimiterToken()); } query.append(" WHERE 1 = 0"); Statement stmt = null; try { stmt = getConnection().createStatement(); ResultSet rs = stmt.executeQuery(query.toString()); ResultSetMetaData rsMetaData = rs.getMetaData(); for (int idx = 0; idx < columnsToCheck.length; idx++) { if (rsMetaData.isAutoIncrement(idx + 1)) { columnsToCheck[idx].setAutoIncrement(true); } } } catch (Exception ex) { final String msg = String.format( "impossible determine AutoIncrement From ResultSetMetaData for table [%s]\ncommand=[%s]\n", table.getName(), query.toString()); _log.warn(msg, ex); for (Column c : table.getColumns()) { _log.trace(String.format("[%s].[%s]\n", table.getName(), c.getName())); } } finally { closeStatement(stmt); } }
From source file:net.ymate.platform.persistence.jdbc.scaffold.EntityGenerator.java
/** * @param dbName ???//from w w w . j av a 2s .c om * @param dbUserName ?? * @param tableName ?? * @return ????? */ private TableMeta getTableMeta(String dbName, String dbUserName, String tableName) { IConnectionHolder _connHolder = null; Statement _statement = null; ResultSet _resultSet = null; Map<String, ColumnInfo> _tableFields = new LinkedHashMap<String, ColumnInfo>(); List<String> _pkFields = new LinkedList<String>(); TableMeta _meta = new TableMeta(_pkFields, _tableFields); try { _connHolder = __jdbc.getDefaultConnectionHolder(); String _dbType = _connHolder.getDialect().getName(); DatabaseMetaData _dbMetaData = _connHolder.getConnection().getMetaData(); System.out.println(">>> Catalog: " + dbName); System.out.println(">>> Schema: " + dbUserName); System.out.println(">>> Table: " + tableName); _resultSet = _dbMetaData.getPrimaryKeys(dbName, _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName); if (_resultSet == null) { System.err.println("Database table \"" + tableName + "\" primaryKey resultSet is null, ignored"); return null; } else { while (_resultSet.next()) { _pkFields.add(_resultSet.getString(4).toLowerCase()); } if (_pkFields.isEmpty()) { System.err .println("Database table \"" + tableName + "\" does not set the primary key, ignored"); return null; } else { // System.out.println(">>> " + "COLUMN_NAME / " + "COLUMN_CLASS_NAME / " + "PRIMARY_KEY / " + "AUTO_INCREMENT / " + "SIGNED / " + "PRECISION / " + "SCALE / " + "NULLABLE / " + "DEFAULT / " + "REMARKS"); // _statement = _connHolder.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); _resultSet = _statement.executeQuery( "SELECT * FROM ".concat(_connHolder.getDialect().wrapIdentifierQuote(tableName))); ResultSetMetaData _rsMetaData = _resultSet.getMetaData(); // for (int _idx = 1; _idx <= _rsMetaData.getColumnCount(); _idx++) { // ?? ResultSet _column = _dbMetaData.getColumns(dbName, _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName, _rsMetaData.getColumnName(_idx)); if (_column.next()) { // ???? _tableFields.put(_rsMetaData.getColumnName(_idx).toLowerCase(), new ColumnInfo(_rsMetaData.getColumnName(_idx).toLowerCase(), _rsMetaData.getColumnClassName(_idx), _rsMetaData.isAutoIncrement(_idx), _rsMetaData.isSigned(_idx), _rsMetaData.getPrecision(_idx), _rsMetaData.getScale(_idx), _rsMetaData.isNullable(_idx), _column.getString("COLUMN_DEF"), _column.getString("REMARKS"))); System.out.println("--> " + _rsMetaData.getColumnName(_idx).toLowerCase() + "\t" + _rsMetaData.getColumnClassName(_idx) + "\t" + _pkFields.contains(_rsMetaData.getColumnName(_idx).toLowerCase()) + "\t" + _rsMetaData.isAutoIncrement(_idx) + "\t" + _rsMetaData.isSigned(_idx) + "\t" + _rsMetaData.getPrecision(_idx) + "\t" + _rsMetaData.getScale(_idx) + "\t" + _rsMetaData.isNullable(_idx) + "\t" + _column.getString("COLUMN_DEF") + "\t" + _column.getString("REMARKS")); } _column.close(); } } } } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } finally { if (_statement != null) { try { _statement.close(); } catch (SQLException e) { _LOG.warn("", e); } } if (_resultSet != null) { try { _resultSet.close(); } catch (SQLException e) { _LOG.warn("", e); } } if (_connHolder != null) { _connHolder.release(); } } return _meta; }
From source file:net.ymate.platform.persistence.jdbc.scaffold.JdbcScaffold.java
/** * @param dbName ???//from ww w .ja v a 2s . co m * @param dbUserName ?? * @param tableName ?? * @return ????? */ private TableMeta getTableMeta(String dbName, String dbUserName, String tableName) { IConnectionHolder _connHolder = null; Statement _statement = null; ResultSet _resultSet = null; Map<String, ColumnInfo> _tableFields = new LinkedHashMap<String, ColumnInfo>(); List<String> _pkFields = new LinkedList<String>(); TableMeta _meta = new TableMeta(_pkFields, _tableFields); try { _connHolder = JDBC.getConnectionHolder(); String _dbType = JDBC_SCAFFOLD_CONF.getProperty("ymp.scaffold.jbdc.db_type", "unknow"); DatabaseMetaData _dbMetaData = _connHolder.getConnection().getMetaData(); _resultSet = _dbMetaData.getPrimaryKeys(dbName, _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName); if (_resultSet == null) { _meta = null; System.err.println("Database table \"" + tableName + "\" primaryKey resultSet is null, ignored"); } else { while (_resultSet.next()) { _pkFields.add(_resultSet.getString(4).toLowerCase()); } if (_pkFields.isEmpty()) { _meta = null; System.err .println("Database table \"" + tableName + "\" does not set the primary key, ignored"); } else { _statement = _connHolder.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); _resultSet = _statement .executeQuery("select * from " + _connHolder.getDialect().wapperQuotedIdent(tableName)); ResultSetMetaData _rsMetaData = _resultSet.getMetaData(); // for (int _idx = 1; _idx <= _rsMetaData.getColumnCount(); _idx++) { // ?? ResultSet _column = _dbMetaData.getColumns(dbName, _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName, _rsMetaData.getColumnName(_idx)); if (_column.next()) { // ???? _tableFields.put(_rsMetaData.getColumnName(_idx).toLowerCase(), new ColumnInfo(_rsMetaData.getColumnName(_idx).toLowerCase(), compressType(_rsMetaData.getColumnClassName(_idx)), _rsMetaData.isAutoIncrement(_idx), _rsMetaData.isNullable(_idx), _column.getString("COLUMN_DEF"))); } } // System.err.println("TABLE_NAME: " + tableName + " ---------------->>"); System.err.println("COLUMN_NAME\tPK\tCOLUMN_TYPE\tIS_AUTOINCREMENT\tIS_NULLABLE\tCOLUMN_DEF"); for (ColumnInfo _cInfo : _tableFields.values()) { System.err .println(_cInfo.getColumnName() + "\t" + _pkFields.contains(_cInfo.getColumnName()) + "\t" + _cInfo.getColumnType() + "\t" + _cInfo.isAutoIncrement() + "\t" + _cInfo.getNullable() + "\t" + _cInfo.getDefaultValue()); } } } } catch (Throwable e) { if (e instanceof Error) { throw (Error) e; } throw new Error(RuntimeUtils.unwrapThrow(e)); } finally { _connHolder.release(); _statement = null; _resultSet = null; } return _meta; }
From source file:org.apache.bigtop.itest.hive.TestJdbc.java
@Test public void preparedStmtAndResultSet() throws SQLException { final String tableName = "bigtop_jdbc_psars_test_table"; try (Statement stmt = conn.createStatement()) { stmt.execute("drop table if exists " + tableName); stmt.execute("create table " + tableName + " (bo boolean, ti tinyint, db double, fl float, " + "i int, lo bigint, sh smallint, st varchar(32))"); }//from w w w. j av a 2 s . co m // NOTE Hive 1.2 theoretically support binary, Date & Timestamp in JDBC, but I get errors when I // try to put them in the query. try (PreparedStatement ps = conn .prepareStatement("insert into " + tableName + " values (?, ?, ?, ?, ?, ?, ?, ?)")) { ps.setBoolean(1, true); ps.setByte(2, (byte) 1); ps.setDouble(3, 3.141592654); ps.setFloat(4, 3.14f); ps.setInt(5, 3); ps.setLong(6, 10L); ps.setShort(7, (short) 20); ps.setString(8, "abc"); ps.executeUpdate(); } try (PreparedStatement ps = conn.prepareStatement("insert into " + tableName + " (i, st) " + "values(?, ?)", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { ps.setNull(1, Types.INTEGER); ps.setObject(2, "mary had a little lamb"); ps.executeUpdate(); ps.setNull(1, Types.INTEGER, null); ps.setString(2, "its fleece was white as snow"); ps.clearParameters(); ps.setNull(1, Types.INTEGER, null); ps.setString(2, "its fleece was white as snow"); ps.execute(); } try (Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from " + tableName); ResultSetMetaData md = rs.getMetaData(); int colCnt = md.getColumnCount(); LOG.debug("Column count is " + colCnt); for (int i = 1; i <= colCnt; i++) { LOG.debug("Looking at column " + i); String strrc = md.getColumnClassName(i); LOG.debug("Column class name is " + strrc); int intrc = md.getColumnDisplaySize(i); LOG.debug("Column display size is " + intrc); strrc = md.getColumnLabel(i); LOG.debug("Column label is " + strrc); strrc = md.getColumnName(i); LOG.debug("Column name is " + strrc); intrc = md.getColumnType(i); LOG.debug("Column type is " + intrc); strrc = md.getColumnTypeName(i); LOG.debug("Column type name is " + strrc); intrc = md.getPrecision(i); LOG.debug("Precision is " + intrc); intrc = md.getScale(i); LOG.debug("Scale is " + intrc); boolean boolrc = md.isAutoIncrement(i); LOG.debug("Is auto increment? " + boolrc); boolrc = md.isCaseSensitive(i); LOG.debug("Is case sensitive? " + boolrc); boolrc = md.isCurrency(i); LOG.debug("Is currency? " + boolrc); intrc = md.getScale(i); LOG.debug("Scale is " + intrc); intrc = md.isNullable(i); LOG.debug("Is nullable? " + intrc); boolrc = md.isReadOnly(i); LOG.debug("Is read only? " + boolrc); } while (rs.next()) { LOG.debug("bo = " + rs.getBoolean(1)); LOG.debug("bo = " + rs.getBoolean("bo")); LOG.debug("ti = " + rs.getByte(2)); LOG.debug("ti = " + rs.getByte("ti")); LOG.debug("db = " + rs.getDouble(3)); LOG.debug("db = " + rs.getDouble("db")); LOG.debug("fl = " + rs.getFloat(4)); LOG.debug("fl = " + rs.getFloat("fl")); LOG.debug("i = " + rs.getInt(5)); LOG.debug("i = " + rs.getInt("i")); LOG.debug("lo = " + rs.getLong(6)); LOG.debug("lo = " + rs.getLong("lo")); LOG.debug("sh = " + rs.getShort(7)); LOG.debug("sh = " + rs.getShort("sh")); LOG.debug("st = " + rs.getString(8)); LOG.debug("st = " + rs.getString("st")); LOG.debug("tm = " + rs.getObject(8)); LOG.debug("tm = " + rs.getObject("st")); LOG.debug("tm was null " + rs.wasNull()); } LOG.debug("bo is column " + rs.findColumn("bo")); int intrc = rs.getConcurrency(); LOG.debug("concurrency " + intrc); intrc = rs.getFetchDirection(); LOG.debug("fetch direction " + intrc); intrc = rs.getType(); LOG.debug("type " + intrc); Statement copy = rs.getStatement(); SQLWarning warning = rs.getWarnings(); while (warning != null) { LOG.debug("Found a warning: " + warning.getMessage()); warning = warning.getNextWarning(); } rs.clearWarnings(); } }
From source file:org.jumpmind.db.platform.AbstractJdbcDdlReader.java
protected void determineAutoIncrementFromResultSetMetaData(Connection conn, Table table, final Column columnsToCheck[], String catalogSeparator) throws SQLException { StringBuilder query = new StringBuilder(); try {// ww w . jav a 2s .co m if (columnsToCheck == null || columnsToCheck.length == 0) { return; } query.append("SELECT "); for (int idx = 0; idx < columnsToCheck.length; idx++) { if (idx > 0) { query.append(","); } query.append("t."); appendIdentifier(query, columnsToCheck[idx].getName()); } query.append(" FROM "); if (table.getCatalog() != null && !table.getCatalog().trim().equals("")) { appendIdentifier(query, table.getCatalog()); query.append(catalogSeparator); } if (table.getSchema() != null && !table.getSchema().trim().equals("")) { appendIdentifier(query, table.getSchema()).append("."); } appendIdentifier(query, table.getName()).append(" t WHERE 1 = 0"); Statement stmt = null; try { stmt = conn.createStatement(); if (log.isDebugEnabled()) { log.debug( "Running the following query to get metadata about whether a column is an auto increment column: \n{}", query); } ResultSet rs = null; try { rs = stmt.executeQuery(query.toString()); ResultSetMetaData rsMetaData = rs.getMetaData(); for (int idx = 0; idx < columnsToCheck.length; idx++) { if (log.isDebugEnabled()) { log.debug(columnsToCheck[idx] + " is auto increment? " + rsMetaData.isAutoIncrement(idx + 1)); } if (rsMetaData.isAutoIncrement(idx + 1)) { columnsToCheck[idx].setAutoIncrement(true); } } } finally { close(rs); } } finally { close(stmt); } } catch (SQLException ex) { StringBuilder msg = new StringBuilder("Failed to determine auto increment columns using this query: '" + query + "'. This is probably not harmful, but should be fixed. "); msg.append("\n"); msg.append(table.toString()); if (columnsToCheck != null) { for (Column col : columnsToCheck) { msg.append("\n"); msg.append(col.toString()); } } log.warn(msg.toString(), ex); } }