Example usage for java.sql ResultSet getShort

List of usage examples for java.sql ResultSet getShort

Introduction

In this page you can find the example usage for java.sql ResultSet getShort.

Prototype

short getShort(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a short in the Java programming language.

Usage

From source file:edu.ku.brc.specify.ui.db.ResultSetTableModel.java

/**
 * @param setter/*from  w w w  .ja va 2  s . c o  m*/
 * @param parent
 * @param fieldName
 * @param fieldClass
 * @param resultSet
 * @param colIndex
 * @throws SQLException
 */
protected void setField(final DataObjectSettable setter, final Object parent, final String fieldName,
        final Class<?> fieldClass, final ResultSet resultSet, final int colIndex) throws SQLException {
    Object fieldDataObj = resultSet.getObject(colIndex + 1);
    //log.debug("fieldName ["+fieldName+"] fieldClass ["+fieldClass.getSimpleName()+"] colIndex [" +  colIndex + "] fieldDataObj [" + fieldDataObj+"]");
    if (fieldDataObj != null) {
        if (fieldClass == String.class) {
            setter.setFieldValue(parent, fieldName, fieldDataObj);

        } else if (fieldClass == Byte.class) {
            setter.setFieldValue(parent, fieldName, resultSet.getByte(colIndex + 1));

        } else if (fieldClass == Short.class) {
            setter.setFieldValue(parent, fieldName, resultSet.getShort(colIndex + 1));

        } else {
            setter.setFieldValue(parent, fieldName, fieldDataObj);
        }
    }
}

From source file:chh.utils.db.source.common.JdbcClient.java

public List<List<Column>> select(String sqlQuery, List<Column> queryParams) {
    Connection connection = null;
    try {// w  w w . j  a  v a  2  s. c o m
        connection = connectionProvider.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
        if (queryTimeoutSecs > 0) {
            preparedStatement.setQueryTimeout(queryTimeoutSecs);
        }
        setPreparedStatementParams(preparedStatement, queryParams);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<List<Column>> rows = Lists.newArrayList();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<Column> row = Lists.newArrayList();
            for (int i = 1; i <= columnCount; i++) {
                String columnLabel = metaData.getColumnLabel(i);
                int columnType = metaData.getColumnType(i);
                Class columnJavaType = Util.getJavaType(columnType);
                if (columnJavaType.equals(String.class)) {
                    row.add(new Column<String>(columnLabel, resultSet.getString(columnLabel), columnType));
                } else if (columnJavaType.equals(Integer.class)) {
                    row.add(new Column<Integer>(columnLabel, resultSet.getInt(columnLabel), columnType));
                } else if (columnJavaType.equals(Double.class)) {
                    row.add(new Column<Double>(columnLabel, resultSet.getDouble(columnLabel), columnType));
                } else if (columnJavaType.equals(Float.class)) {
                    row.add(new Column<Float>(columnLabel, resultSet.getFloat(columnLabel), columnType));
                } else if (columnJavaType.equals(Short.class)) {
                    row.add(new Column<Short>(columnLabel, resultSet.getShort(columnLabel), columnType));
                } else if (columnJavaType.equals(Boolean.class)) {
                    row.add(new Column<Boolean>(columnLabel, resultSet.getBoolean(columnLabel), columnType));
                } else if (columnJavaType.equals(byte[].class)) {
                    row.add(new Column<byte[]>(columnLabel, resultSet.getBytes(columnLabel), columnType));
                } else if (columnJavaType.equals(Long.class)) {
                    row.add(new Column<Long>(columnLabel, resultSet.getLong(columnLabel), columnType));
                } else if (columnJavaType.equals(Date.class)) {
                    row.add(new Column<Date>(columnLabel, resultSet.getDate(columnLabel), columnType));
                } else if (columnJavaType.equals(Time.class)) {
                    row.add(new Column<Time>(columnLabel, resultSet.getTime(columnLabel), columnType));
                } else if (columnJavaType.equals(Timestamp.class)) {
                    row.add(new Column<Timestamp>(columnLabel, resultSet.getTimestamp(columnLabel),
                            columnType));
                } else {
                    throw new RuntimeException(
                            "type =  " + columnType + " for column " + columnLabel + " not supported.");
                }
            }
            rows.add(row);
        }
        return rows;
    } catch (SQLException e) {
        throw new RuntimeException("Failed to execute select query " + sqlQuery, e);
    } finally {
        closeConnection(connection);
    }
}

From source file:forseti.admon.JAdmCFDDlg.java

public void Cambiar(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    short idmensaje = -1;
    String mensaje = "", claveret = "";

    String rfc = p(JUtil.fco(JUtil.frfc(request.getParameter("rfc"))));

    String str = "select * from sp_cfd_cambiar('" + getSesion(request).getConBD() + "','"
            + p(request.getParameter("cfd_regimenfiscal")) + "','" + rfc + "','" +
            // certificados fiscales digitales
            p(request.getParameter("cfd")) + "','" + p(request.getParameter("cfd_calle")) + "','"
            + p(request.getParameter("cfd_noext")) + "','" + p(request.getParameter("cfd_noint")) + "','"
            + p(request.getParameter("cfd_colonia")) + "','" + p(request.getParameter("cfd_localidad")) + "','"
            + p(request.getParameter("cfd_municipio")) + "','" + p(request.getParameter("cfd_estado")) + "','"
            + p(request.getParameter("cfd_pais")) + "','" + p(request.getParameter("cfd_cp"))
            + "') as ( err integer, res varchar, clave varchar ) ";

    // Primero cambia el RFC en la variable del sistema local
    JRetFuncBas rfb = new JRetFuncBas();
    String sel = "SELECT * FROM sp_variables_cambiar('RFC',null,null,null,'" + rfc
            + "') as ( err integer, res varchar, clave varchar ) ";
    doCallStoredProcedure(request, response, sel, rfb);
    if (rfb.getIdmensaje() == 0) {
        sel = "SELECT * FROM sp_variables_cambiar('EMPRESA',null,null,null,'"
                + p(JUtil.getSesion(request).getNombreCompania())
                + "') as ( err integer, res varchar, clave varchar ) ";
        doCallStoredProcedure(request, response, sel, rfb);
    }/*www  .  ja v a  2s  .c om*/
    //Ahora cambia el registro completo de FORSETI_ADMIN
    if (rfb.getIdmensaje() == 0) {
        // No llama al procedimiento normal, porque se conecta a la base de datos administrativa *doCallStoredProcedure(request, response, str, rfb);
        try {
            Connection con = JAccesoBD.getConexion();
            Statement s = con.createStatement();
            ResultSet rs = s.executeQuery(str);
            if (rs.next()) {
                idmensaje = rs.getShort("ERR");
                mensaje = rs.getString("RES");
                claveret = rs.getString("CLAVE");
            }
            s.close();
            JAccesoBD.liberarConexion(con);
        } catch (SQLException e) {
            idmensaje = 4;
            mensaje = q(e.getMessage());
        }
    } else {
        idmensaje = (short) rfb.getIdmensaje();
        mensaje = rfb.getRes();
    }

    RDP("CEF", getSesion(request).getConBD(), (idmensaje == 0 ? "OK" : (idmensaje == 4 ? "AL" : "ER")),
            getSesion(request).getID_Usuario(), "ADM_CFDI_AGREGAR", "ACFD|" + claveret + "|||", mensaje);
    getSesion(request).setID_Mensaje(idmensaje, mensaje);
    irApag("/forsetiweb/administracion/adm_cfd_dlg.jsp", request, response);
}

From source file:net.certifi.audittablegen.GenericDMR.java

public Map<String, DataTypeDef> getDataTypes() {

    if (this.dataTypes != null) {
        return this.dataTypes;
    }/*from   w  w w  . j  a v a 2  s . c o  m*/

    //this is kind of ugly.  Some databases (postgres) return the VALUES of
    //metadata in lowercase, while others (hsqldb) return the VALUES of
    //metadata in uppercase.  This is why the key values are stored as
    //case insensitive - so it will work with default types for 
    Map<String, DataTypeDef> types = new CaseInsensitiveMap();

    try {
        Connection conn = dataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getTypeInfo();

        if (!rs.isBeforeFirst()) {
            throw new RuntimeException("No results for DatabaseMetaData.getTypeInfo()");
        }
        while (rs.next()) {

            DataTypeDef dtd = new DataTypeDef();

            dtd.type_name = rs.getString("TYPE_NAME");
            dtd.data_type = rs.getInt("DATA_TYPE");
            dtd.precision = rs.getInt("PRECISION");
            dtd.literal_prefix = rs.getString("LITERAL_PREFIX");
            dtd.literal_suffix = rs.getString("LITERAL_SUFFIX");
            dtd.create_params = rs.getString("CREATE_PARAMS");
            dtd.nullable = rs.getShort("NULLABLE");
            dtd.case_sensitive = rs.getBoolean("CASE_SENSITIVE");
            dtd.searchable = rs.getShort("SEARCHABLE");
            dtd.unsigned_attribute = rs.getBoolean("UNSIGNED_ATTRIBUTE");
            dtd.fixed_prec_scale = rs.getBoolean("FIXED_PREC_SCALE");
            dtd.auto_increment = rs.getBoolean("AUTO_INCREMENT");
            dtd.local_type_name = rs.getString("LOCAL_TYPE_NAME");
            dtd.minimum_scale = rs.getShort("MINIMUM_SCALE");
            dtd.maximum_scale = rs.getShort("MAXIMUM_SCALE");
            dtd.sql_data_type = rs.getInt("SQL_DATA_TYPE"); //not used
            dtd.sql_datetime_sub = rs.getInt("SQL_DATETIME_SUB"); //not used
            dtd.num_prec_radix = rs.getInt("NUM_PREC_RADIX");

            //google guava primitive types tools
            if (Ints.contains(DataTypeDef.sqlSizedTypes, dtd.data_type) && !dtd.type_name.equals("text")) {
                dtd.createWithSize = true;
            }

            types.put(dtd.type_name, dtd);

        }

    } catch (SQLException e) {
        throw Throwables.propagate(e);
    }

    this.dataTypes = types;

    Collection<String> debugValues = types.keySet();
    for (String debugValue : debugValues) {
        logger.debug("DB has type value {}", debugValue);

    }

    return types;

}

From source file:com.netspective.axiom.policy.AnsiDatabasePolicy.java

public void reverseEngineer(Writer writer, Connection conn, String catalog, String schemaPattern)
        throws IOException, SQLException {
    Map dataTypesMap = prepareJdbcTypeInfoMap();
    DatabaseMetaData dbmd = conn.getMetaData();
    TextUtils textUtils = TextUtils.getInstance();

    writer.write("<?xml version=\"1.0\"?>\n\n");
    writer.write("<!-- Reverse engineered by Axiom\n");
    writer.write("     driver: " + dbmd.getDriverName() + "\n");
    writer.write("     driver-version: " + dbmd.getDriverVersion() + "\n");
    writer.write("     product: " + dbmd.getDatabaseProductName() + "\n");
    writer.write("     product-version: " + dbmd.getDatabaseProductVersion() + "\n");

    writer.write("     available catalogs:");
    ResultSet rs = null;//ww  w  . j  av a  2 s  .  c  om
    try {
        rs = dbmd.getCatalogs();
        while (rs.next()) {
            writer.write(" " + rs.getObject(1).toString());
        }
    } finally {
        if (rs != null)
            rs.close();
    }

    writer.write("\n");

    writer.write("     available schemas:");
    try {
        rs = dbmd.getSchemas();
        while (rs.next()) {
            writer.write(" " + rs.getObject(1).toString());
        }
    } finally {
        if (rs != null)
            rs.close();
    }
    writer.write("\n");
    writer.write("-->\n\n");

    writer.write("<component xmlns:xdm=\"http://www.netspective.org/Framework/Commons/XMLDataModel\">\n");
    writer.write("    <xdm:include resource=\"com/netspective/axiom/conf/axiom.xml\"/>\n");
    writer.write("    <schema name=\"" + catalog + "." + schemaPattern + "\">\n");

    Map dbmdTypeInfoByName = new HashMap();
    Map dbmdTypeInfoByJdbcType = new HashMap();
    ResultSet typesRS = null;
    try {
        typesRS = dbmd.getTypeInfo();
        while (typesRS.next()) {
            int colCount = typesRS.getMetaData().getColumnCount();
            Object[] typeInfo = new Object[colCount];
            for (int i = 1; i <= colCount; i++)
                typeInfo[i - 1] = typesRS.getObject(i);
            dbmdTypeInfoByName.put(typesRS.getString(1), typeInfo);
            dbmdTypeInfoByJdbcType.put(new Integer(typesRS.getInt(2)), typeInfo);
        }
    } finally {
        if (typesRS != null)
            typesRS.close();
    }

    ResultSet tables = null;
    try {
        tables = dbmd.getTables(catalog, schemaPattern, null, new String[] { "TABLE" });
        while (tables.next()) {
            String tableNameOrig = tables.getString(3);
            String tableName = textUtils.fixupTableNameCase(tableNameOrig);

            writer.write("        <table name=\"" + tableName + "\">\n");

            Map primaryKeys = new HashMap();
            ResultSet pkRS = null;
            try {
                pkRS = dbmd.getPrimaryKeys(null, null, tableNameOrig);
                while (pkRS.next()) {
                    primaryKeys.put(pkRS.getString(4), pkRS.getString(5));
                }

            } catch (Exception e) {
                // driver may not support this function
            } finally {
                if (pkRS != null)
                    pkRS.close();
            }

            Map fKeys = new HashMap();
            ResultSet fkRS = null;
            try {
                fkRS = dbmd.getImportedKeys(null, null, tableNameOrig);
                while (fkRS.next()) {
                    fKeys.put(fkRS.getString(8), textUtils.fixupTableNameCase(fkRS.getString(3)) + "."
                            + fkRS.getString(4).toLowerCase());
                }
            } catch (Exception e) {
                // driver may not support this function
            } finally {
                if (fkRS != null)
                    fkRS.close();
            }

            // we keep track of processed columns so we don't duplicate them in the XML
            Set processedColsMap = new HashSet();
            ResultSet columns = null;
            try {
                columns = dbmd.getColumns(null, null, tableNameOrig, null);
                while (columns.next()) {
                    String columnNameOrig = columns.getString(4);
                    if (processedColsMap.contains(columnNameOrig))
                        continue;
                    processedColsMap.add(columnNameOrig);

                    String columnName = columnNameOrig.toLowerCase();

                    writer.write("            <column name=\"" + columnName + "\"");
                    try {
                        if (fKeys.containsKey(columnNameOrig))
                            writer.write(" lookup-ref=\"" + fKeys.get(columnNameOrig) + "\"");
                        else {
                            short jdbcType = columns.getShort(5);
                            String dataType = (String) dataTypesMap.get(new Integer(jdbcType));
                            if (dataType == null)
                                dataType = Short.toString(jdbcType);
                            writer.write(" type=\"" + dataType + "\"");
                        }

                        if (primaryKeys.containsKey(columnNameOrig))
                            writer.write(" primary-key=\"yes\"");

                        if (columns.getString(18).equals("NO"))
                            writer.write(" required=\"yes\"");

                        String defaultValue = columns.getString(13);
                        if (defaultValue != null)
                            writer.write(" default=\"" + defaultValue + "\"");

                        String remarks = columns.getString(12);
                        if (remarks != null)
                            writer.write(" descr=\"" + remarks + "\"");

                    } catch (Exception e) {
                    }

                    writer.write("/>\n");
                }
            } finally {
                if (columns != null)
                    columns.close();
            }

            writer.write("        </table>\n");
        }
    } finally {
        tables.close();
    }

    writer.write("    </schema>\n");
    writer.write("</component>");
}

From source file:gsn.wrappers.JDBCWrapper.java

public void run() {
    DataEnumerator data;/*from  ww w. java2s .  co  m*/

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    }

    Connection conn = null;
    ResultSet resultSet = null;

    while (isActive()) {
        try {
            conn = sm.getConnection();
            StringBuilder query = new StringBuilder("select * from ").append(table_name)
                    .append(" where timed > " + latest_timed + " limit 0," + buffer_size);

            resultSet = sm.executeQueryWithResultSet(query, conn);

            //logger.debug(query);

            while (resultSet.next()) {
                Serializable[] output = new Serializable[this.getOutputFormat().length];

                long pk = resultSet.getLong(1);
                long timed = resultSet.getLong(2);

                //logger.warn("pk => "+ pk);
                //logger.warn("timed => "+ timed);

                for (int i = 0; i < dataFieldsLength; i++) {

                    switch (dataFieldTypes[i]) {
                    case DataTypes.VARCHAR:
                    case DataTypes.CHAR:
                        output[i] = resultSet.getString(i + 3);
                        break;
                    case DataTypes.INTEGER:
                        output[i] = resultSet.getInt(i + 3);
                        break;
                    case DataTypes.TINYINT:
                        output[i] = resultSet.getByte(i + 3);
                        break;
                    case DataTypes.SMALLINT:
                        output[i] = resultSet.getShort(i + 3);
                        break;
                    case DataTypes.DOUBLE:
                        output[i] = resultSet.getDouble(i + 3);
                        break;
                    case DataTypes.FLOAT:
                        output[i] = resultSet.getFloat(i + 3);
                        break;
                    case DataTypes.BIGINT:
                        output[i] = resultSet.getLong(i + 3);
                        break;
                    case DataTypes.BINARY:
                        output[i] = resultSet.getBytes(i + 3);
                        break;
                    }
                    //logger.warn(i+" (type: "+dataFieldTypes[i]+" ) => "+output[i]);
                }

                StreamElement se = new StreamElement(dataFieldNames, dataFieldTypes, output, timed);
                latest_timed = se.getTimeStamp();

                //logger.warn(" Latest => " + latest_timed);

                this.postStreamElement(se);

                updateCheckPointFile(latest_timed);

                //logger.warn(se);
            }

        } catch (java.io.IOException e) {
            logger.error(e.getMessage(), e);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        } finally {
            sm.close(resultSet);
            sm.close(conn);
        }

        try {
            Thread.sleep(rate);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:ResultSetIterator.java

/**
 * Convert a <code>ResultSet</code> column into an object.  Simple 
 * implementations could just call <code>rs.getObject(index)</code> while
 * more complex implementations could perform type manipulation to match 
 * the column's type to the bean property type.
 * //from  ww w. j a  va  2 s.c o m
 * <p>
 * This implementation calls the appropriate <code>ResultSet</code> getter 
 * method for the given property type to perform the type conversion.  If 
 * the property type doesn't match one of the supported 
 * <code>ResultSet</code> types, <code>getObject</code> is called.
 * </p>
 * 
 * @param rs The <code>ResultSet</code> currently being processed.  It is
 * positioned on a valid row before being passed into this method.
 * 
 * @param index The current column index being processed.
 * 
 * @param propType The bean property type that this column needs to be
 * converted into.
 * 
 * @throws SQLException if a database access error occurs
 * 
 * @return The object from the <code>ResultSet</code> at the given column
 * index after optional type processing or <code>null</code> if the column
 * value was SQL NULL.
 */
protected Object processColumn(ResultSet rs, int index, Class propType) throws SQLException {

    if (!propType.isPrimitive() && rs.getObject(index) == null) {
        return null;
    }

    if (propType.equals(String.class)) {
        return rs.getString(index);

    } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
        return new Integer(rs.getInt(index));

    } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
        return new Boolean(rs.getBoolean(index));

    } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
        return new Long(rs.getLong(index));

    } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) {
        return new Double(rs.getDouble(index));

    } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) {
        return new Float(rs.getFloat(index));

    } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) {
        return new Short(rs.getShort(index));

    } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
        return new Byte(rs.getByte(index));

    } else if (propType.equals(Timestamp.class)) {
        return rs.getTimestamp(index);

    } else {
        return rs.getObject(index);
    }

}

From source file:com.nextep.designer.sqlgen.generic.impl.JDBCCapturer.java

/**
 * Returns a <code>UniqueKeyConstraint</code> object representing the
 * primary key of the specified table present in the data source pointed to
 * by the connection object provided by the specified <code>context</code>
 * and notifies the specified <code>monitor</code> while capturing.
 * /*from   w w  w  .j  a v  a 2 s.c  o m*/
 * @param context
 *            a {@link ICaptureContext} to store the captured objects
 * @param monitor
 *            the {@link IProgressMonitor} to notify while capturing objects
 * @param allTablesColumns
 *            a <code>Map</code> of all columns previously captured
 * @param table
 *            the {@link IBasicTable} for which the primary key must be
 *            captured
 * @return a {@link UniqueKeyConstraint} object if the specified table has a
 *         primary key, <code>null</code> otherwise
 */
private UniqueKeyConstraint getTablePrimaryKey(ICaptureContext context, IProgressMonitor monitor,
        Map<String, IBasicColumn> allTablesColumns, IBasicTable table) {
    UniqueKeyConstraint pk = null;

    final String tableName = table.getName();
    try {
        final DatabaseMetaData md = ((Connection) context.getConnectionObject()).getMetaData();

        ResultSet rset = null;
        if (md != null) {
            rset = md.getPrimaryKeys(getObjectOrContextCatalog(context, table),
                    getObjectOrContextSchema(context, table), tableName);
            CaptureHelper.updateMonitor(monitor, getCounter(), 1, 1);
        }

        if (rset != null) {
            ColumnsSorter pkColumnsSorter = null;

            try {
                while (rset.next()) {
                    final String pkName = rset.getString(COLUMN_NAME_PK_NAME);
                    final String pkColumnName = rset.getString(COLUMN_NAME_COLUMN_NAME);

                    /*
                     * We need to fetch the column's index in the primary
                     * key because columns are ordered by COLUMN_NAME in the
                     * ResultSet.
                     */
                    final short position = rset.getShort(COLUMN_NAME_KEY_SEQ);

                    if (pkName != null && !"".equals(pkName.trim())) { //$NON-NLS-1$
                        if (LOGGER.isDebugEnabled()) {
                            String logPrefix = "[" + tableName + "][" + pkName + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            LOGGER.debug("= " + logPrefix + " Primary Key Metadata ="); //$NON-NLS-1$ //$NON-NLS-2$
                            LOGGER.debug(logPrefix + "[" + COLUMN_NAME_COLUMN_NAME + "] " //$NON-NLS-1$ //$NON-NLS-2$
                                    + pkColumnName);
                            LOGGER.debug(logPrefix + "[" + COLUMN_NAME_KEY_SEQ + "] " //$NON-NLS-1$ //$NON-NLS-2$
                                    + position);
                        }

                        if (null == pk) {
                            pk = typedObjFactory.create(UniqueKeyConstraint.class);
                            pk.setName(getConnectionVendor(context).getNameFormatter().format(pkName));
                            pk.setConstraintType(ConstraintType.PRIMARY);
                            pkColumnsSorter = new ColumnsSorter();
                        }

                        if (pkColumnsSorter != null && pkColumnName != null
                                && !"".equals(pkColumnName.trim())) { //$NON-NLS-1$
                            final IBasicColumn pkColumn = allTablesColumns
                                    .get(CaptureHelper.getUniqueObjectName(tableName, pkColumnName));
                            if (pkColumn != null) {
                                pkColumnsSorter.addColumn(pkColumn, position);
                            } else {
                                // TODO [BGA]: Raise a warning and manage
                                // the PK creation
                                // cancellation
                            }
                        }
                    }
                }
            } finally {
                CaptureHelper.safeClose(rset, null);
            }

            if (pk != null && pkColumnsSorter != null) {
                int index = 0;
                for (IBasicColumn column : pkColumnsSorter.getColumnsSortedArray()) {
                    pk.addConstrainedColumn(index++, column);
                }
            }
        }
    } catch (SQLException sqle) {
        LOGGER.error("Unable to fetch primary key for table [" + tableName + "] from "
                + getConnectionVendorName(context) + " server: " + sqle.getMessage(), sqle);
    }

    return pk;
}

From source file:gsn.wrappers.TetraedreNMCWrapper.java

public void run() {
    DataEnumerator data;/*from ww w .  jav  a  2  s  .  co  m*/

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    }

    Connection conn = null;
    ResultSet resultSet = null;

    while (isActive()) {
        try {
            conn = sm.getConnection();
            StringBuilder query = new StringBuilder("select * from ").append(table_name).append(
                    " where timestamp*1000 > " + latest_timed + "  order by timestamp limit 0," + buffer_size);

            resultSet = sm.executeQueryWithResultSet(query, conn);

            //logger.debug(query);

            while (resultSet.next()) {
                Serializable[] output = new Serializable[this.getOutputFormat().length];

                //long pk = resultSet.getLong(1);
                long timed = resultSet.getLong(1) * 1000;

                //logger.warn("pk => "+ pk);
                //logger.warn("timed => "+ timed);

                for (int i = 0; i < dataFieldsLength; i++) {

                    switch (dataFieldTypes[i]) {
                    case DataTypes.VARCHAR:
                    case DataTypes.CHAR:
                        output[i] = resultSet.getString(i + 1);
                        break;
                    case DataTypes.INTEGER:
                        output[i] = resultSet.getInt(i + 1);
                        break;
                    case DataTypes.TINYINT:
                        output[i] = resultSet.getByte(i + 1);
                        break;
                    case DataTypes.SMALLINT:
                        output[i] = resultSet.getShort(i + 1);
                        break;
                    case DataTypes.DOUBLE:
                        output[i] = resultSet.getDouble(i + 1);
                        break;
                    case DataTypes.FLOAT:
                        output[i] = resultSet.getFloat(i + 1);
                        break;
                    case DataTypes.BIGINT:
                        output[i] = resultSet.getLong(i + 1);
                        break;
                    case DataTypes.BINARY:
                        output[i] = resultSet.getBytes(i + 1);
                        break;
                    }
                    //logger.warn(i+" (type: "+dataFieldTypes[i]+" ) => "+output[i]);
                }

                StreamElement se = new StreamElement(dataFieldNames, dataFieldTypes, output, timed);
                latest_timed = se.getTimeStamp();

                //logger.warn(" Latest => " + latest_timed);

                this.postStreamElement(se);

                updateCheckPointFile(latest_timed);

                //logger.warn(se);
            }

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        } finally {
            sm.close(resultSet);
            sm.close(conn);
        }

        try {
            Thread.sleep(rate);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:fsi_admin.JFsiTareas.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public synchronized void actualizarSaldos() {
    //       Primero recopila la informacion de las bases de datos.
    Vector BASES = new Vector();

    JBDRegistradasSet bdr = new JBDRegistradasSet(null);
    bdr.ConCat(true);// w w  w. jav  a2 s.  co m
    bdr.Open();

    for (int i = 0; i < bdr.getNumRows(); i++) {
        String nombre = bdr.getAbsRow(i).getNombre();
        BASES.addElement(nombre);

    }
    short res = 0;
    String mensaje = "";
    Connection con;

    try {
        Calendar fecha = GregorianCalendar.getInstance();
        FileWriter filewri = new FileWriter(
                "/usr/local/forseti/log/SLDS-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-hh-mm") + ".log", true);
        PrintWriter pw = new PrintWriter(filewri);

        for (int i = 0; i < BASES.size(); i++) {
            String nombre = (String) BASES.get(i);

            pw.println("----------------------------------------------------------------------------");
            pw.println("             " + "ACTUALIZANDO LA BASE DE DATOS: " + nombre + " "
                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
            pw.println("----------------------------------------------------------------------------");
            pw.flush();

            System.out.println("ACTUALIZANDO LA BASE DE DATOS: " + nombre + " "
                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));

            //Empieza por la de saldos
            con = JAccesoBD.getConexion(nombre);
            String sql[] = {
                    "select * from sp_invserv_actualizar_existencias() as ( err integer, res varchar ) ",
                    "select * from sp_prod_formulas_actualizar_niveles() as ( err integer, res varchar ) ",
                    "select * from sp_invserv_actualizar_sdos() as ( err integer, res varchar ) ",
                    "select * from sp_invserv_actualizar_polcant() as ( err integer, res varchar ) ",
                    "select * from sp_cont_catalogo_actualizar_sdos() as ( err integer, res varchar ) ",
                    "select * from sp_bancos_actualizar_sdos() as ( err integer, res varchar ) ",
                    "select * from sp_provee_actualizar_sdos() as ( err integer, res varchar ) ",
                    "select * from sp_client_actualizar_sdos() as ( err integer, res varchar ) " };

            try {
                Statement s = con.createStatement();
                for (int j = 0; j < sql.length; j++) {
                    System.out.println("EJECUTANDO: " + sql[j]);
                    pw.println("EJECUTANDO: " + sql[j] + "\n");
                    pw.flush();

                    ResultSet rs = s.executeQuery(sql[j]);
                    if (rs.next()) {
                        res = rs.getShort("ERR");
                        mensaje = rs.getString("RES");
                    }

                    //outprintln("REGRESO: ERR: " + res + " RES: " + mensaje + " " + JUtil.obtFechaTxt(new Date(), "hh:mm:ss"));
                    pw.println("REGRESO: ERR: " + res + " RES: " + mensaje + " "
                            + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
                    pw.flush();

                }
                s.close();

            } catch (NullPointerException e) //Se captura cuando no existe una base de datos fsica pero el cabecero general de tbl_bd contiene una
            {
                System.out.println(e.toString());
                pw.println(e.toString() + "\n");
                pw.flush();
            } catch (SQLException e) {
                System.out.println(e.toString());
                pw.println(e.toString() + "\n");
                pw.flush();
            } finally {
                JAccesoBD.liberarConexion(con);
            }

        } // Fin for BA>SES

        pw.println("----------------------------- FIN DE LA ACTUALIZACION ----------------------------------");
        pw.flush();

        idsalida = 0;
    } catch (IOException e) {
        idsalida = 3;
        salida += "OCURRIERON ERRORES AL ABRIR O COPIAR ARCHIVOS... REVISA EL REGISTRO DE ACTUALIZACIONES<br>";
        e.printStackTrace();
    }

}