Example usage for java.sql ResultSetMetaData isNullable

List of usage examples for java.sql ResultSetMetaData isNullable

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData isNullable.

Prototype

int isNullable(int column) throws SQLException;

Source Link

Document

Indicates the nullability of values in the designated column.

Usage

From source file:org.apache.kylin.rest.service.QueryService.java

/**
 * @param correctedSql// w  w w .j a  va 2  s . c  om
 * @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:net.ymate.platform.persistence.jdbc.scaffold.JdbcScaffold.java

/**
 * @param dbName ???//from  ww  w  .j  a  v a  2 s  . c  o 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:net.ymate.platform.persistence.jdbc.scaffold.EntityGenerator.java

/**
 * @param dbName     ???/*from  www.j  a v  a  2 s .  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:org.geoserver.taskmanager.tasks.CopyTableTaskTypeImpl.java

@Override
public TaskResult run(TaskContext ctx) throws TaskException {
    // TODO: check for ctx.isInterruptMe() in loops and cancel task

    final DbSource sourcedb = (DbSource) ctx.getParameterValues().get(PARAM_SOURCE_DB_NAME);
    final DbSource targetdb = (DbSource) ctx.getParameterValues().get(PARAM_TARGET_DB_NAME);
    final DbTable table = (DbTable) ctx.getBatchContext().get(ctx.getParameterValues().get(PARAM_TABLE_NAME));

    final DbTable targetTable = ctx.getParameterValues().containsKey(PARAM_TARGET_TABLE_NAME)
            ? (DbTable) ctx.getParameterValues().get(PARAM_TARGET_TABLE_NAME)
            : new DbTableImpl(targetdb, table.getTableName());
    final String tempTableName = SqlUtil.qualified(SqlUtil.schema(targetTable.getTableName()),
            "_temp_" + UUID.randomUUID().toString().replace('-', '_'));
    ctx.getBatchContext().put(targetTable, new DbTableImpl(targetdb, tempTableName));

    try (Connection sourceConn = sourcedb.getDataSource().getConnection()) {
        sourceConn.setAutoCommit(false);
        try (Connection destConn = targetdb.getDataSource().getConnection()) {
            try (Statement stmt = sourceConn.createStatement()) {
                stmt.setFetchSize(BATCH_SIZE);
                try (ResultSet rs = stmt
                        .executeQuery("SELECT * FROM " + sourcedb.getDialect().quote(table.getTableName()))) {

                    ResultSetMetaData rsmd = rs.getMetaData();

                    String tempSchema = SqlUtil.schema(tempTableName);
                    String sqlCreateSchemaIfNotExists = tempSchema == null ? ""
                            : targetdb.getDialect().createSchema(destConn,
                                    targetdb.getDialect().quote(tempSchema));

                    // create the temp table structure
                    StringBuilder sb = new StringBuilder(sqlCreateSchemaIfNotExists);
                    sb.append("CREATE TABLE ").append(targetdb.getDialect().quote(tempTableName)).append(" ( ");
                    int columnCount = rsmd.getColumnCount();

                    for (int i = 1; i <= columnCount; i++) {
                        String columnName = targetdb.getDialect().quote(rsmd.getColumnLabel(i));
                        String typeName = rsmd.getColumnTypeName(i);
                        sb.append(columnName).append(" ").append(typeName);
                        if (("char".equals(typeName) || "varchar".equals(typeName))
                                && rsmd.getColumnDisplaySize(i) > 0
                                && rsmd.getColumnDisplaySize(i) < Integer.MAX_VALUE) {
                            sb.append(" (").append(rsmd.getColumnDisplaySize(i)).append(" ) ");
                        }/*from w  w w  . jav a 2  s  .co m*/
                        switch (sourcedb.getDialect().isNullable(rsmd.isNullable(i))) {
                        case ResultSetMetaData.columnNoNulls:
                            sb.append(" NOT NULL");
                            break;
                        case ResultSetMetaData.columnNullable:
                            sb.append(" NULL");
                            break;
                        }
                        sb.append(", ");
                    }
                    String primaryKey = getPrimaryKey(sourceConn, table.getTableName());
                    boolean hasPrimaryKeyColumn = !primaryKey.isEmpty();
                    if (!hasPrimaryKeyColumn) {
                        // create a Primary key column if none exist.
                        sb.append(GENERATE_ID_COLUMN_NAME + " int PRIMARY KEY, ");
                        columnCount++;
                    }

                    sb.setLength(sb.length() - 2);
                    sb.append(" ); ");

                    // creating indexes
                    Map<String, Set<String>> indexAndColumnMap = getIndexesColumns(sourceConn,
                            table.getTableName());
                    Set<String> uniqueIndexes = getUniqueIndexes(sourceConn, table.getTableName());
                    Set<String> spatialColumns = sourcedb.getDialect().getSpatialColumns(sourceConn,
                            table.getTableName(), sourcedb.getSchema());

                    for (String indexName : indexAndColumnMap.keySet()) {
                        Set<String> columnNames = indexAndColumnMap.get(indexName);
                        boolean isSpatialIndex = columnNames.size() == 1
                                && spatialColumns.contains(columnNames.iterator().next());

                        sb.append(targetdb.getDialect().createIndex(tempTableName, columnNames, isSpatialIndex,
                                uniqueIndexes.contains(indexName)));
                    }
                    // we are copying a view and need to create the spatial index.
                    if (indexAndColumnMap.isEmpty() && !spatialColumns.isEmpty()) {
                        sb.append(
                                targetdb.getDialect().createIndex(tempTableName, spatialColumns, true, false));
                    }

                    String dump = sb.toString();
                    LOGGER.log(Level.FINE, "creating temporary table: " + dump);

                    try (Statement stmt2 = destConn.createStatement()) {
                        stmt2.executeUpdate(dump);
                    }

                    // copy the data
                    sb = new StringBuilder("INSERT INTO ").append(targetdb.getDialect().quote(tempTableName))
                            .append(" VALUES (");
                    for (int i = 0; i < columnCount; i++) {
                        if (i > 0) {
                            sb.append(",");
                        }
                        sb.append("?");
                    }
                    sb.append(")");

                    LOGGER.log(Level.FINE, "inserting records: " + sb.toString());

                    try (PreparedStatement pstmt = destConn.prepareStatement(sb.toString())) {
                        int batchSize = 0;
                        int primaryKeyValue = 0;
                        while (rs.next()) {
                            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                                pstmt.setObject(i, rs.getObject(i));
                            }
                            // generate the primary key value
                            if (!hasPrimaryKeyColumn) {
                                pstmt.setObject(columnCount, primaryKeyValue);
                            }
                            pstmt.addBatch();
                            batchSize++;
                            if (batchSize >= BATCH_SIZE) {
                                pstmt.executeBatch();
                                batchSize = 0;
                            }
                            primaryKeyValue++;
                        }
                        if (batchSize > 0) {
                            pstmt.executeBatch();
                        }
                    }
                }
            }
        }
    } catch (SQLException e) {
        // clean-up if necessary
        try (Connection conn = targetdb.getDataSource().getConnection()) {
            try (Statement stmt = conn.createStatement()) {
                stmt.executeUpdate("DROP TABLE IF EXISTS " + targetdb.getDialect().quote(tempTableName));
            }
        } catch (SQLException e2) {
        }

        throw new TaskException(e);
    }

    return new TaskResult() {
        @Override
        public void commit() throws TaskException {
            try (Connection conn = targetdb.getDataSource().getConnection()) {
                try (Statement stmt = conn.createStatement()) {
                    stmt.executeUpdate(
                            "DROP TABLE IF EXISTS " + targetdb.getDialect().quote(targetTable.getTableName()));
                    stmt.executeUpdate("ALTER TABLE " + targetdb.getDialect().quote(tempTableName)
                            + " RENAME TO "
                            + targetdb.getDialect().quote(SqlUtil.notQualified(targetTable.getTableName())));
                }

                ctx.getBatchContext().delete(targetTable);
            } catch (SQLException e) {
                throw new TaskException(e);
            }
        }

        @Override
        public void rollback() throws TaskException {
            try (Connection conn = targetdb.getDataSource().getConnection()) {
                try (Statement stmt = conn.createStatement()) {
                    stmt.executeUpdate("DROP TABLE " + targetdb.getDialect().quote(tempTableName) + "");
                }
            } catch (SQLException e) {
                throw new TaskException(e);
            }
        }
    };
}

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   www  .  j a v 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.agnitas.dao.impl.RecipientDaoImpl.java

@Override
public CaseInsensitiveMap<CsvColInfo> readDBColumns(int companyID) {
    String sqlGetTblStruct = "SELECT * FROM customer_" + companyID + "_tbl WHERE 1=0";
    CsvColInfo aCol = null;//from www . j ava2 s.  co  m
    int colType;
    CaseInsensitiveMap<CsvColInfo> dbAllColumns = new CaseInsensitiveMap<CsvColInfo>();
    DataSource ds = (DataSource) this.applicationContext.getBean("dataSource");
    Connection con = DataSourceUtils.getConnection(ds);
    try {
        Statement stmt = con.createStatement();
        ResultSet rset = stmt.executeQuery(sqlGetTblStruct);
        ResultSetMetaData meta = rset.getMetaData();

        for (int i = 1; i <= meta.getColumnCount(); i++) {
            if (!meta.getColumnName(i).equals("change_date") && !meta.getColumnName(i).equals("creation_date")
                    && !meta.getColumnName(i).equals("datasource_id")) {
                //                  if (meta.getColumnName(i).equals("customer_id")) {
                //                     if (status == null) {
                //                        initStatus(getWebApplicationContext());
                //                     }
                //                     if (!( mode == ImportWizardServiceImpleImpl.MODE_ONLY_UPDATE && status.getKeycolumn().equals("customer_id"))) {
                //                        continue;
                //                     }
                //                  }

                aCol = new CsvColInfo();
                aCol.setName(meta.getColumnName(i));
                aCol.setLength(meta.getColumnDisplaySize(i));
                aCol.setType(CsvColInfo.TYPE_UNKNOWN);
                aCol.setActive(false);
                aCol.setNullable(meta.isNullable(i) != 0);

                colType = meta.getColumnType(i);
                aCol.setType(dbTypeToCsvType(colType));
                dbAllColumns.put(meta.getColumnName(i), aCol);
            }
        }
        rset.close();
        stmt.close();
    } catch (Exception e) {
        logger.error("readDBColumns (companyID: " + companyID + ")", e);
    }
    DataSourceUtils.releaseConnection(con, ds);
    return dbAllColumns;
}

From source file:org.sakaiproject.util.foorm.Foorm.java

/**
 * /*from w ww. j a  v  a 2 s.  co  m*/
 * @param table
 * @param formDefinition
 * @param vendor
 * @param md
 * @return
 */
public String[] formAdjustTable(String table, String[] formDefinition, String vendor, ResultSetMetaData md) {
    ArrayList<String> rv = new ArrayList<String>();

    for (String formField : formDefinition) {
        Properties info = parseFormString(formField);
        String field = info.getProperty("field", null);
        String type = info.getProperty("type", null);
        if ("header".equals(type))
            continue;
        String maxs = adjustMax(info.getProperty("maxlength", null));
        int maxlength = 0;
        if (maxs != null)
            maxlength = (new Integer(maxs)).intValue();
        if (maxlength < 1)
            maxlength = 80;

        String sqlType = null;
        boolean autoIncrement = false;
        int sqlLength = -1;
        boolean isNullable = false;
        try {
            for (int i = 1; i <= md.getColumnCount(); i++) {
                if (field.equalsIgnoreCase(md.getColumnLabel(i))) {
                    sqlLength = md.getColumnDisplaySize(i);
                    autoIncrement = md.isAutoIncrement(i);
                    sqlType = getSuperType(md.getColumnClassName(i));
                    isNullable = (md.isNullable(i) == ResultSetMetaData.columnNullable);
                    break;
                }
            }
        } catch (Exception e) {
            // ignore
        }

        logger.fine(field + " (" + maxlength + ") type=" + type);
        logger.fine(field + " (" + sqlLength + ") auto=" + autoIncrement + " type=" + sqlType + " null="
                + isNullable);

        //  If the field is not there...
        if (sqlType == null) {
            if ("oracle".equals(vendor)) {
                rv.add("ALTER TABLE " + table + " ADD ( " + formSql(formField, vendor) + " )");
            } else if ("mysql".equals(vendor)) {
                rv.add("ALTER TABLE " + table + " ADD " + formSql(formField, vendor));
            } else {
                rv.add("ALTER TABLE " + table + " ADD COLUMN " + formSql(formField, vendor));
            }
            continue;
        }

        String ff = formSql(formField, vendor);

        // BLTI-220, BLTI-238 - Required will be enforced in software - not the DB
        boolean shouldAlter = false;
        if ("key".equals(type)) {
            if (!NUMBER_TYPE.equals(sqlType))
                logger.severe(field + " must be Integer and Auto Increment");
        } else if ("autodate".equals(type)) {
        } else if ("url".equals(type) || "text".equals(type) || "textarea".equals(type)) {
            if ("oracle.sql.CLOB".equals(sqlType) || "oracle.jdbc.OracleClob".equals(sqlType))
                continue; // CLOBS large enough :)
            if (!STRING_TYPE.equals(sqlType)) {
                logger.severe(field + " must be String field");
                continue;
            }
            if (sqlLength < maxlength)
                shouldAlter = true;
            if (!isNullable)
                shouldAlter = true; // BLTI-220, BLTI-238
        } else if ("radio".equals(type) || "checkbox".equals(type) || "integer".equals(type)) {
            if (NUMBER_TYPE.equals(sqlType))
                continue;
            logger.severe(field + " must be Integer field");
        }

        if (shouldAlter) {
            if ("oracle".equals(vendor)) {
                rv.add("ALTER TABLE " + table + " MODIFY ( " + ff + " )");
            } else if ("mysql".equals(vendor)) {
                rv.add("ALTER TABLE " + table + " MODIFY " + ff);
            } else {
                rv.add("ALTER TABLE " + table + " ALTER COLUMN " + ff);
            }
        }
    }

    return rv.toArray(new String[rv.size()]);
}

From source file:com.egt.core.db.xdp.RecursoCachedRowSetDataProvider.java

private boolean isNullableColumn(String fieldId) {
    try {//from   w ww .j ava  2  s  .c om
        ResultSetMetaData rsmd = this.getCachedRowSet().getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        for (int i = 1; i <= numberOfColumns; i++) {
            if (rsmd.getColumnName(i).equalsIgnoreCase(fieldId)) {
                if (rsmd.isNullable(i) == ResultSetMetaData.columnNullable) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    } catch (Exception ex) {
        TLC.getBitacora().fatal(ex);
    }
    return false;
}

From source file:uk.ac.ed.epcc.webapp.model.data.Repository.java

/**
 * Use a ResultSet to populate the MetaData information
 * //from   w ww.jav a 2  s.c  om
 * @param rs
 * @throws SQLException
 * @throws ConsistencyError
 */
private void setMetaData(ResultSet rs) throws SQLException, ConsistencyError {
    assert (fields == null);
    fields = new LinkedHashMap<String, FieldInfo>();
    ResultSetMetaData meta_data = rs.getMetaData();
    int md_columns = meta_data.getColumnCount();
    boolean seen_key = false;
    // Logger log = ctx.getLogger(getClass());
    for (int i = 1; i <= md_columns; i++) {
        String returned_name = meta_data.getTableName(i);
        if (returned_name.length() > 0 && !returned_name.equalsIgnoreCase(table_name)) {
            throw new ConsistencyError("Table names do not match " + getTag() + "!=" + returned_name);
        }
        // if we don't know for sure assume no nulls
        boolean can_null = (meta_data.isNullable(i) == ResultSetMetaData.columnNullable);
        String name = meta_data.getColumnName(i);
        if (!seen_key && meta_data.isAutoIncrement(i)) {
            seen_key = true;
            id_name = name;
        } else {
            // log.debug("Metadata "+name+" "+meta_data.getColumnType(i));
            int columnType = meta_data.getColumnType(i);
            int columnDisplaySize = meta_data.getColumnDisplaySize(i);
            fields.put(dbFieldtoTag(name), new FieldInfo(name, columnType, columnDisplaySize, can_null));
        }
    }
    if (use_id && !seen_key) {
        // Note we need an up-to-date mysql driver for the isAutoIncrement
        // method to work properly. otherwise default to first col and hope
        id_name = meta_data.getColumnName(1);
        fields.remove(dbFieldtoTag(id_name));
    }
    // cache the qualified form as this is used frequently
    StringBuilder sb = new StringBuilder();
    sb.append(alias_name);
    sb.append(".");
    sb.append(id_name);
    qualified_id_name = sb.toString();
}

From source file:ips1ap101.lib.core.db.xdp.RecursoCachedRowSetDataProvider.java

private boolean isNullableColumn(String fieldId) {
    try {/*from w  w w. ja  v a2  s .c  om*/
        ResultSetMetaData rsmd = getCachedRowSet().getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        for (int i = 1; i <= numberOfColumns; i++) {
            if (rsmd.getColumnName(i).equalsIgnoreCase(fieldId)) {
                if (rsmd.isNullable(i) == ResultSetMetaData.columnNullable) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    } catch (Exception ex) {
        TLC.getBitacora().fatal(ex);
    }
    return false;
}