Example usage for java.sql Types FLOAT

List of usage examples for java.sql Types FLOAT

Introduction

In this page you can find the example usage for java.sql Types FLOAT.

Prototype

int FLOAT

To view the source code for java.sql Types FLOAT.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type FLOAT.

Usage

From source file:com.flexive.core.storage.GenericDivisionExporter.java

/**
 * Dump a generic table to XML// w  w w  . j  av  a 2s  . com
 *
 * @param tableName     name of the table
 * @param stmt          an open statement
 * @param out           output stream
 * @param sb            an available and valid StringBuilder
 * @param xmlTag        name of the xml tag to write per row
 * @param idColumn      (optional) id column to sort results
 * @param onlyBinaries  process binary fields (else these will be ignored)
 * @throws SQLException on errors
 * @throws IOException  on errors
 */
private void dumpTable(String tableName, Statement stmt, OutputStream out, StringBuilder sb, String xmlTag,
        String idColumn, boolean onlyBinaries) throws SQLException, IOException {
    ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName
            + (StringUtils.isEmpty(idColumn) ? "" : " ORDER BY " + idColumn + " ASC"));
    final ResultSetMetaData md = rs.getMetaData();
    String value, att;
    boolean hasSubTags;
    while (rs.next()) {
        hasSubTags = false;
        if (!onlyBinaries) {
            sb.setLength(0);
            sb.append("  <").append(xmlTag);
        }
        for (int i = 1; i <= md.getColumnCount(); i++) {
            value = null;
            att = md.getColumnName(i).toLowerCase();
            switch (md.getColumnType(i)) {
            case java.sql.Types.DECIMAL:
            case java.sql.Types.NUMERIC:
            case java.sql.Types.BIGINT:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getBigDecimal(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.INTEGER:
            case java.sql.Types.SMALLINT:
            case java.sql.Types.TINYINT:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getLong(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.DOUBLE:
            case java.sql.Types.FLOAT:
            case java.sql.Types.REAL:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getDouble(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.TIMESTAMP:
            case java.sql.Types.DATE:
                if (!onlyBinaries) {
                    final Timestamp ts = rs.getTimestamp(i);
                    if (rs.wasNull())
                        value = null;
                    else
                        value = FxFormatUtils.getDateTimeFormat().format(ts);
                }
                break;
            case java.sql.Types.BIT:
            case java.sql.Types.CHAR:
            case java.sql.Types.BOOLEAN:
                if (!onlyBinaries) {
                    value = rs.getBoolean(i) ? "1" : "0";
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.CLOB:
            case java.sql.Types.BLOB:
            case java.sql.Types.LONGVARBINARY:
            case java.sql.Types.LONGVARCHAR:
            case java.sql.Types.VARBINARY:
            case java.sql.Types.VARCHAR:
            case java.sql.Types.BINARY:
            case SQL_LONGNVARCHAR:
            case SQL_NCHAR:
            case SQL_NCLOB:
            case SQL_NVARCHAR:

                hasSubTags = true;
                break;
            default:
                LOG.warn("Unhandled type [" + md.getColumnType(i) + "] for [" + tableName + "." + att + "]");
            }
            if (value != null && !onlyBinaries)
                sb.append(' ').append(att).append("=\"").append(value).append("\"");
        }
        if (hasSubTags) {
            if (!onlyBinaries)
                sb.append(">\n");
            for (int i = 1; i <= md.getColumnCount(); i++) {
                switch (md.getColumnType(i)) {
                case java.sql.Types.VARBINARY:
                case java.sql.Types.LONGVARBINARY:
                case java.sql.Types.BLOB:
                case java.sql.Types.BINARY:
                    if (idColumn == null)
                        throw new IllegalArgumentException("Id column required to process binaries!");
                    String binFile = FOLDER_BINARY + "/BIN_" + String.valueOf(rs.getLong(idColumn)) + "_" + i
                            + ".blob";
                    att = md.getColumnName(i).toLowerCase();
                    if (onlyBinaries) {
                        if (!(out instanceof ZipOutputStream))
                            throw new IllegalArgumentException(
                                    "out has to be a ZipOutputStream to store binaries!");
                        ZipOutputStream zip = (ZipOutputStream) out;
                        InputStream in = rs.getBinaryStream(i);
                        if (rs.wasNull())
                            break;

                        ZipEntry ze = new ZipEntry(binFile);
                        zip.putNextEntry(ze);

                        byte[] buffer = new byte[4096];
                        int read;
                        while ((read = in.read(buffer)) != -1)
                            zip.write(buffer, 0, read);
                        in.close();
                        zip.closeEntry();
                        zip.flush();
                    } else {
                        InputStream in = rs.getBinaryStream(i); //need to fetch to see if it is empty
                        if (rs.wasNull())
                            break;
                        in.close();
                        sb.append("    <").append(att).append(">").append(binFile).append("</").append(att)
                                .append(">\n");
                    }
                    break;
                case java.sql.Types.CLOB:
                case SQL_LONGNVARCHAR:
                case SQL_NCHAR:
                case SQL_NCLOB:
                case SQL_NVARCHAR:
                case java.sql.Types.LONGVARCHAR:
                case java.sql.Types.VARCHAR:
                    if (!onlyBinaries) {
                        value = rs.getString(i);
                        if (rs.wasNull())
                            break;
                        att = md.getColumnName(i).toLowerCase();
                        sb.append("    <").append(att).append('>');
                        escape(sb, value);
                        sb.append("</").append(att).append(">\n");
                    }
                    break;
                }
            }
            if (!onlyBinaries)
                sb.append("  </").append(xmlTag).append(">\n");
        } else {
            if (!onlyBinaries)
                sb.append("/>\n");
        }
        if (!onlyBinaries)
            write(out, sb);
    }
}

From source file:org.sakaiproject.webservices.SakaiReport.java

protected String toCsvString(ResultSet rs, boolean includeHeaderRow) throws IOException, SQLException {
    StringWriter stringWriter = new StringWriter();
    CsvWriter writer = new CsvWriter(stringWriter, ',');
    writer.setRecordDelimiter('\n');
    writer.setForceQualifier(true);//from w  ww .j av  a2s  .  co  m
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();

    if (includeHeaderRow) {
        String[] row = new String[numColumns];
        for (int i = 1; i < numColumns + 1; i++) {
            row[i - 1] = rsmd.getColumnLabel(i);
        }
        writer.writeRecord(row);
    }

    while (rs.next()) {
        String[] row = new String[numColumns];
        for (int i = 1; i < numColumns + 1; i++) {

            String column_name = rsmd.getColumnName(i);

            LOG.debug("Column Name=" + column_name + ",type=" + rsmd.getColumnType(i));

            switch (rsmd.getColumnType(i)) {
            case Types.BIGINT:
                row[i - 1] = String.valueOf(rs.getInt(i));
                break;
            case Types.BOOLEAN:
                row[i - 1] = String.valueOf(rs.getBoolean(i));
                break;
            case Types.BLOB:
                row[i - 1] = rs.getBlob(i).toString();
                break;
            case Types.DOUBLE:
                row[i - 1] = String.valueOf(rs.getDouble(i));
                break;
            case Types.FLOAT:
                row[i - 1] = String.valueOf(rs.getFloat(i));
                break;
            case Types.INTEGER:
                row[i - 1] = String.valueOf(rs.getInt(i));
                break;
            case Types.LONGVARCHAR:
                row[i - 1] = rs.getString(i);
                break;
            case Types.NVARCHAR:
                row[i - 1] = rs.getNString(i);
                break;
            case Types.VARCHAR:
                row[i - 1] = rs.getString(i);
                break;
            case Types.TINYINT:
                row[i - 1] = String.valueOf(rs.getInt(i));
                break;
            case Types.SMALLINT:
                row[i - 1] = String.valueOf(rs.getInt(i));
                break;
            case Types.DATE:
                row[i - 1] = rs.getDate(i).toString();
                break;
            case Types.TIMESTAMP:
                row[i - 1] = rs.getTimestamp(i).toString();
                break;
            default:
                row[i - 1] = rs.getString(i);
                break;

            }
            LOG.debug("value: " + row[i - 1]);
        }
        writer.writeRecord(row);
        //writer.endRecord();

    }

    LOG.debug("csv output:" + stringWriter.toString());

    return stringWriter.toString();
}

From source file:org.jfree.data.jdbc.JDBCXYDataset.java

/**
 * ExecuteQuery will attempt execute the query passed to it against the
 * provided database connection.  If connection is null then no action is
 * taken./*from  w w  w  .  j a  v  a  2s  .  com*/
 *
 * The results from the query are extracted and cached locally, thus
 * applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param  query  the query to be executed.
 * @param  con  the connection the query is to be executed against.
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    if (con == null) {
        throw new SQLException("There is no database to execute the query.");
    }

    ResultSet resultSet = null;
    Statement statement = null;
    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int numberOfColumns = metaData.getColumnCount();
        int numberOfValidColumns = 0;
        int[] columnTypes = new int[numberOfColumns];
        for (int column = 0; column < numberOfColumns; column++) {
            try {
                int type = metaData.getColumnType(column + 1);
                switch (type) {

                case Types.NUMERIC:
                case Types.REAL:
                case Types.INTEGER:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.DECIMAL:
                case Types.BIT:
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP:
                case Types.BIGINT:
                case Types.SMALLINT:
                    ++numberOfValidColumns;
                    columnTypes[column] = type;
                    break;
                default:
                    columnTypes[column] = Types.NULL;
                    break;
                }
            } catch (SQLException e) {
                columnTypes[column] = Types.NULL;
                throw e;
            }
        }

        if (numberOfValidColumns <= 1) {
            throw new SQLException("Not enough valid columns where generated by query.");
        }

        /// First column is X data
        this.columnNames = new String[numberOfValidColumns - 1];
        /// Get the column names and cache them.
        int currentColumn = 0;
        for (int column = 1; column < numberOfColumns; column++) {
            if (columnTypes[column] != Types.NULL) {
                this.columnNames[currentColumn] = metaData.getColumnLabel(column + 1);
                ++currentColumn;
            }
        }

        // Might need to add, to free memory from any previous result sets
        if (this.rows != null) {
            for (int column = 0; column < this.rows.size(); column++) {
                ArrayList row = (ArrayList) this.rows.get(column);
                row.clear();
            }
            this.rows.clear();
        }

        // Are we working with a time series.
        switch (columnTypes[0]) {
        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            this.isTimeSeries = true;
            break;
        default:
            this.isTimeSeries = false;
            break;
        }

        // Get all rows.
        // rows = new ArrayList();
        while (resultSet.next()) {
            ArrayList newRow = new ArrayList();
            for (int column = 0; column < numberOfColumns; column++) {
                Object xObject = resultSet.getObject(column + 1);
                switch (columnTypes[column]) {
                case Types.NUMERIC:
                case Types.REAL:
                case Types.INTEGER:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.DECIMAL:
                case Types.BIGINT:
                case Types.SMALLINT:
                    newRow.add(xObject);
                    break;

                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP:
                    newRow.add(new Long(((Date) xObject).getTime()));
                    break;
                case Types.NULL:
                    break;
                default:
                    System.err.println("Unknown data");
                    columnTypes[column] = Types.NULL;
                    break;
                }
            }
            this.rows.add(newRow);
        }

        /// a kludge to make everything work when no rows returned
        if (this.rows.size() == 0) {
            ArrayList newRow = new ArrayList();
            for (int column = 0; column < numberOfColumns; column++) {
                if (columnTypes[column] != Types.NULL) {
                    newRow.add(new Integer(0));
                }
            }
            this.rows.add(newRow);
        }

        /// Determine max and min values.
        if (this.rows.size() < 1) {
            this.maxValue = 0.0;
            this.minValue = 0.0;
        } else {
            ArrayList row = (ArrayList) this.rows.get(0);
            this.maxValue = Double.NEGATIVE_INFINITY;
            this.minValue = Double.POSITIVE_INFINITY;
            for (int rowNum = 0; rowNum < this.rows.size(); ++rowNum) {
                row = (ArrayList) this.rows.get(rowNum);
                for (int column = 1; column < numberOfColumns; column++) {
                    Object testValue = row.get(column);
                    if (testValue != null) {
                        double test = ((Number) testValue).doubleValue();

                        if (test < this.minValue) {
                            this.minValue = test;
                        }
                        if (test > this.maxValue) {
                            this.maxValue = test;
                        }
                    }
                }
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                // TODO: is this a good idea?
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                // TODO: is this a good idea?
            }
        }
    }

}

From source file:org.pentaho.di.jdbc.Support.java

/**
 * Convert an existing data object to the specified JDBC type.
 *
 * @param callerReference an object reference to the caller of this method;
 *                        must be a <code>Connection</code>,
 *                        <code>Statement</code> or <code>ResultSet</code>
 * @param x               the data object to convert
 * @param jdbcType        the required type constant from
 *                        <code>java.sql.Types</code>
 * @return the converted data object/*from   w  ww .j a va  2s. c om*/
 * @throws SQLException if the conversion is not supported or fails
 */
static Object convert(Object callerReference, Object x, int jdbcType, String charSet) throws SQLException {
    try {
        switch (jdbcType) {
        case java.sql.Types.TINYINT:
        case java.sql.Types.SMALLINT:
        case java.sql.Types.INTEGER:
            if (x == null) {
                return INTEGER_ZERO;
            } else if (x instanceof Integer) {
                return x;
            } else if (x instanceof Byte) {
                return new Integer(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Integer(((Number) x).intValue());
            } else if (x instanceof String) {
                return new Integer(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
            }
            break;

        case java.sql.Types.BIGINT:
            if (x == null) {
                return LONG_ZERO;
            } else if (x instanceof Long) {
                return x;
            } else if (x instanceof Byte) {
                return new Long(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Long(((Number) x).longValue());
            } else if (x instanceof String) {
                return new Long(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO;
            }

            break;

        case java.sql.Types.REAL:
            if (x == null) {
                return FLOAT_ZERO;
            } else if (x instanceof Float) {
                return x;
            } else if (x instanceof Byte) {
                return new Float(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Float(((Number) x).floatValue());
            } else if (x instanceof String) {
                return new Float(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO;
            }

            break;

        case java.sql.Types.FLOAT:
        case java.sql.Types.DOUBLE:
            if (x == null) {
                return DOUBLE_ZERO;
            } else if (x instanceof Double) {
                return x;
            } else if (x instanceof Byte) {
                return new Double(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Double(((Number) x).doubleValue());
            } else if (x instanceof String) {
                return new Double(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO;
            }

            break;

        case java.sql.Types.NUMERIC:
        case java.sql.Types.DECIMAL:
            if (x == null) {
                return null;
            } else if (x instanceof BigDecimal) {
                return x;
            } else if (x instanceof Number) {
                return new BigDecimal(x.toString());
            } else if (x instanceof String) {
                return new BigDecimal((String) x);
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO;
            }

            break;

        case java.sql.Types.VARCHAR:
        case java.sql.Types.CHAR:
            if (x == null) {
                return null;
            } else if (x instanceof String) {
                return x;
            } else if (x instanceof Number) {
                return x.toString();
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? "1" : "0";
            } else if (x instanceof Clob) {
                Clob clob = (Clob) x;
                long length = clob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                return clob.getSubString(1, (int) length);
            } else if (x instanceof Blob) {
                Blob blob = (Blob) x;
                long length = blob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                x = blob.getBytes(1, (int) length);
            }

            if (x instanceof byte[]) {
                return toHex((byte[]) x);
            }

            return x.toString(); // Last hope!

        case java.sql.Types.BIT:
        case java.sql.Types.BOOLEAN:
            if (x == null) {
                return Boolean.FALSE;
            } else if (x instanceof Boolean) {
                return x;
            } else if (x instanceof Number) {
                return (((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE;
            } else if (x instanceof String) {
                String tmp = ((String) x).trim();

                return ("1".equals(tmp) || "true".equalsIgnoreCase(tmp)) ? Boolean.TRUE : Boolean.FALSE;
            }

            break;

        case java.sql.Types.VARBINARY:
        case java.sql.Types.BINARY:
            if (x == null) {
                return null;
            } else if (x instanceof byte[]) {
                return x;
            } else if (x instanceof Blob) {
                Blob blob = (Blob) x;

                return blob.getBytes(1, (int) blob.length());
            } else if (x instanceof Clob) {
                Clob clob = (Clob) x;
                long length = clob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                x = clob.getSubString(1, (int) length);
            }

            if (x instanceof String) {
                //
                // Strictly speaking this conversion is not required by
                // the JDBC standard but jTDS has always supported it.
                //
                if (charSet == null) {
                    charSet = "ISO-8859-1";
                }

                try {
                    return ((String) x).getBytes(charSet);
                } catch (UnsupportedEncodingException e) {
                    return ((String) x).getBytes();
                }
            } else if (x instanceof UniqueIdentifier) {
                return ((UniqueIdentifier) x).getBytes();
            }

            break;

        case java.sql.Types.TIMESTAMP:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toTimestamp();
            } else if (x instanceof java.sql.Timestamp) {
                return x;
            } else if (x instanceof java.sql.Date) {
                return new java.sql.Timestamp(((java.sql.Date) x).getTime());
            } else if (x instanceof java.sql.Time) {
                return new java.sql.Timestamp(((java.sql.Time) x).getTime());
            } else if (x instanceof java.lang.String) {
                return java.sql.Timestamp.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.DATE:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toDate();
            } else if (x instanceof java.sql.Date) {
                return x;
            } else if (x instanceof java.sql.Time) {
                return DATE_ZERO;
            } else if (x instanceof java.sql.Timestamp) {
                synchronized (cal) {
                    cal.setTime((java.util.Date) x);
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);
                    // VM1.4+ only              return new java.sql.Date(cal.getTimeInMillis());
                    return new java.sql.Date(cal.getTime().getTime());
                }
            } else if (x instanceof java.lang.String) {
                return java.sql.Date.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.TIME:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toTime();
            } else if (x instanceof java.sql.Time) {
                return x;
            } else if (x instanceof java.sql.Date) {
                return TIME_ZERO;
            } else if (x instanceof java.sql.Timestamp) {
                synchronized (cal) {
                    // VM 1.4+ only             cal.setTimeInMillis(((java.sql.Timestamp)x).getTime());
                    cal.setTime((java.util.Date) x);
                    cal.set(Calendar.YEAR, 1970);
                    cal.set(Calendar.MONTH, 0);
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    // VM 1.4+ only             return new java.sql.Time(cal.getTimeInMillis());*/
                    return new java.sql.Time(cal.getTime().getTime());
                }
            } else if (x instanceof java.lang.String) {
                return java.sql.Time.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.OTHER:
            return x;

        case java.sql.Types.JAVA_OBJECT:
            throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(),
                    getJdbcTypeName(jdbcType)), "22005");

        case java.sql.Types.LONGVARBINARY:
        case java.sql.Types.BLOB:
            if (x == null) {
                return null;
            } else if (x instanceof Blob) {
                return x;
            } else if (x instanceof byte[]) {
                return new BlobImpl(getConnection(callerReference), (byte[]) x);
            } else if (x instanceof Clob) {
                //
                // Convert CLOB to BLOB. Not required by the standard but we will
                // do it anyway.
                //
                Clob clob = (Clob) x;
                try {
                    if (charSet == null) {
                        charSet = "ISO-8859-1";
                    }
                    Reader rdr = clob.getCharacterStream();
                    BlobImpl blob = new BlobImpl(getConnection(callerReference));
                    BufferedWriter out = new BufferedWriter(
                            new OutputStreamWriter(blob.setBinaryStream(1), charSet));
                    // TODO Use a buffer to improve performance
                    int c;
                    while ((c = rdr.read()) >= 0) {
                        out.write(c);
                    }
                    out.close();
                    rdr.close();
                    return blob;
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen but fall back on in memory copy
                    x = clob.getSubString(1, (int) clob.length());
                } catch (IOException e) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()),
                            "HY000");
                }
            }

            if (x instanceof String) {
                //
                // Strictly speaking this conversion is also not required by
                // the JDBC standard but jTDS has always supported it.
                //
                BlobImpl blob = new BlobImpl(getConnection(callerReference));
                String data = (String) x;

                if (charSet == null) {
                    charSet = "ISO-8859-1";
                }

                try {
                    blob.setBytes(1, data.getBytes(charSet));
                } catch (UnsupportedEncodingException e) {
                    blob.setBytes(1, data.getBytes());
                }

                return blob;
            }

            break;

        case java.sql.Types.LONGVARCHAR:
        case java.sql.Types.CLOB:
            if (x == null) {
                return null;
            } else if (x instanceof Clob) {
                return x;
            } else if (x instanceof Blob) {
                //
                // Convert BLOB to CLOB
                //
                Blob blob = (Blob) x;
                try {
                    InputStream is = blob.getBinaryStream();
                    ClobImpl clob = new ClobImpl(getConnection(callerReference));
                    Writer out = clob.setCharacterStream(1);
                    // TODO Use a buffer to improve performance
                    int b;
                    // These reads/writes are buffered by the undelying blob buffers
                    while ((b = is.read()) >= 0) {
                        out.write(hex[b >> 4]);
                        out.write(hex[b & 0x0F]);
                    }
                    out.close();
                    is.close();
                    return clob;
                } catch (IOException e) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()),
                            "HY000");
                }
            } else if (x instanceof Boolean) {
                x = ((Boolean) x).booleanValue() ? "1" : "0";
            } else if (!(x instanceof byte[])) {
                x = x.toString();
            }

            if (x instanceof byte[]) {
                ClobImpl clob = new ClobImpl(getConnection(callerReference));
                clob.setString(1, toHex((byte[]) x));

                return clob;
            } else if (x instanceof String) {
                return new ClobImpl(getConnection(callerReference), (String) x);
            }

            break;

        default:
            throw new SQLException(
                    BaseMessages.getString(PKG, "error.convert.badtypeconst", getJdbcTypeName(jdbcType)),
                    "HY004");
        }

        throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(),
                getJdbcTypeName(jdbcType)), "22005");
    } catch (NumberFormatException nfe) {
        throw new SQLException(
                BaseMessages.getString(PKG, "error.convert.badnumber", getJdbcTypeName(jdbcType)), "22000");
    }
}

From source file:org.trafodion.rest.util.JdbcT2Util.java

private synchronized JSONArray convertResultSetToJSON(java.sql.ResultSet rs) throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug("Begin convertResultSetToJSON");

    JSONArray json = new JSONArray();

    try {//ww w. j  a  va  2 s .co  m

        java.sql.ResultSetMetaData rsmd = rs.getMetaData();

        while (rs.next()) {
            int numColumns = rsmd.getColumnCount();
            JSONObject obj = new JSONObject();

            for (int i = 1; i < numColumns + 1; i++) {

                String column_name = rsmd.getColumnName(i);

                if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                    obj.put(column_name, rs.getArray(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                    obj.put(column_name, rs.getLong(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                    obj.put(column_name, rs.getBoolean(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                    obj.put(column_name, rs.getBlob(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                    obj.put(column_name, rs.getDouble(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                    obj.put(column_name, rs.getFloat(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                    obj.put(column_name, rs.getInt(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                    obj.put(column_name, rs.getNString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR
                        || rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                    //prevent obj.put from removing null key value from JSONObject
                    String s = rs.getString(column_name);
                    if (s == null)
                        obj.put(column_name, new String(""));
                    else
                        obj.put(column_name, rs.getString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                    obj.put(column_name, rs.getInt(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                    obj.put(column_name, rs.getInt(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                    obj.put(column_name, rs.getDate(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                    obj.put(column_name, rs.getTimestamp(column_name));
                } else {
                    obj.put(column_name, rs.getObject(column_name));
                }

            } //end foreach 
            json.put(obj);

        } //end while 

    } catch (SQLException e) {
        e.printStackTrace();
        if (LOG.isDebugEnabled())
            LOG.error(e.getMessage());
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        if (LOG.isDebugEnabled())
            LOG.error(e.getMessage());
        throw e;
    }

    if (LOG.isDebugEnabled())
        LOG.debug("End convertResultSetToJSON");

    return json;
}

From source file:com.squid.core.domain.operators.ExtendedType.java

/**
 * compute a type "order" that can be used to compare types and promote types.
 * The order is a couple (x,y), where x represent a family type (string,date,numbers) and y an order in that family
 * A type should be promoted to the higher order.
 * @return//from  w w  w  . j  a v  a  2 s.  com
 */
public int[] computeTypeOrder() {
    switch (getDataType()) {
    case Types.BIT:
        return new int[] { NUMBER_ORDER, 0 };
    case Types.BOOLEAN:
        return new int[] { NUMBER_ORDER, 1 };
    case Types.TINYINT:
        return new int[] { NUMBER_ORDER, 2 };
    case Types.SMALLINT:
        return new int[] { NUMBER_ORDER, 3 };
    case Types.INTEGER:
        return new int[] { NUMBER_ORDER, 4 };
    case Types.BIGINT:
        return new int[] { NUMBER_ORDER, 5 };
    ///////////////////////////
    case Types.REAL:
        return new int[] { NUMBER_ORDER, 6 };
    case Types.DOUBLE:
    case Types.FLOAT:
        return new int[] { NUMBER_ORDER, 7 };
    case Types.DECIMAL:
        return new int[] { NUMBER_ORDER, 8 };
    case Types.NUMERIC:
        return new int[] { NUMBER_ORDER, 9 };
    //////////////////////////
    case Types.CHAR:
        return new int[] { STRING_ORDER, 0 };
    case Types.VARCHAR:
        return new int[] { STRING_ORDER, 1 };
    case Types.LONGVARCHAR:
        return new int[] { STRING_ORDER, 2 };
    case Types.CLOB:
        return new int[] { STRING_ORDER, 3 };
    ///////////////////////////
    case Types.TIME:
        return new int[] { DATE_ORDER, 1 };
    case Types.DATE:
        return new int[] { DATE_ORDER, 2 };
    case Types.TIMESTAMP:
        return new int[] { DATE_ORDER, 3 };
    case CustomTypes.INTERVAL:
        return new int[] { DATE_ORDER, 4 };
    ///////////////////////////
    default:
        return new int[] { UNKNOWN_ORDER, 0 };
    }
}

From source file:org.apache.hadoop.sqoop.manager.SqlManager.java

public String toJavaType(int sqlType) {
    // mappings from http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
    if (sqlType == Types.INTEGER) {
        return "Integer";
    } else if (sqlType == Types.VARCHAR) {
        return "String";
    } else if (sqlType == Types.CHAR) {
        return "String";
    } else if (sqlType == Types.LONGVARCHAR) {
        return "String";
    } else if (sqlType == Types.NUMERIC) {
        return "java.math.BigDecimal";
    } else if (sqlType == Types.DECIMAL) {
        return "java.math.BigDecimal";
    } else if (sqlType == Types.BIT) {
        return "Boolean";
    } else if (sqlType == Types.BOOLEAN) {
        return "Boolean";
    } else if (sqlType == Types.TINYINT) {
        return "Integer";
    } else if (sqlType == Types.SMALLINT) {
        return "Integer";
    } else if (sqlType == Types.BIGINT) {
        return "Long";
    } else if (sqlType == Types.REAL) {
        return "Float";
    } else if (sqlType == Types.FLOAT) {
        return "Double";
    } else if (sqlType == Types.DOUBLE) {
        return "Double";
    } else if (sqlType == Types.DATE) {
        return "java.sql.Date";
    } else if (sqlType == Types.TIME) {
        return "java.sql.Time";
    } else if (sqlType == Types.TIMESTAMP) {
        return "java.sql.Timestamp";
    } else {//from w  w  w .  j av  a2  s .c  o m
        // TODO(aaron): Support BINARY, VARBINARY, LONGVARBINARY, DISTINCT, CLOB, BLOB, ARRAY,
        // STRUCT, REF, JAVA_OBJECT.
        return null;
    }
}

From source file:org.latticesoft.util.resource.dao.Param.java

private Object readValue(ResultSet rs) throws SQLException {
    Object retVal = null;// w  w  w.j  ava2 s  .c  om
    switch (this.sqlType) {
    case Types.VARCHAR:
    case Types.CHAR:
        String s = null;
        if (this.getSqlIndex() == 0) {
            s = rs.getString(this.getSqlName());
        } else {
            s = rs.getString(this.getSqlIndex());
        }
        retVal = s;
        break;
    case Types.BOOLEAN:
        boolean b = false;
        if (this.getSqlIndex() == 0) {
            b = rs.getBoolean(this.getSqlName());
        } else {
            b = rs.getBoolean(this.getSqlIndex());
        }
        retVal = new Boolean(b);
        break;
    case Types.INTEGER:
        int i = 0;
        if (this.getSqlIndex() == 0) {
            i = rs.getInt(this.getSqlName());
        } else {
            i = rs.getInt(this.getSqlIndex());
        }
        retVal = new Integer(i);
        break;
    case Types.SMALLINT:
        short ss = 0;
        if (this.getSqlIndex() == 0) {
            ss = rs.getShort(this.getSqlName());
        } else {
            ss = rs.getShort(this.getSqlIndex());
        }
        retVal = new Short(ss);
        break;
    case Types.TINYINT:
        byte bb = 0;
        if (this.getSqlIndex() == 0) {
            bb = rs.getByte(this.getSqlName());
        } else {
            bb = rs.getByte(this.getSqlIndex());
        }
        retVal = new Byte(bb);
        break;
    case Types.BIGINT:
        long l = 0;
        if (this.getSqlIndex() == 0) {
            l = rs.getLong(this.getSqlName());
        } else {
            l = rs.getLong(this.getSqlIndex());
        }
        retVal = new Long(l);
        break;
    case Types.DOUBLE:
        double dd = 0;
        if (this.getSqlIndex() == 0) {
            dd = rs.getDouble(this.getSqlName());
        } else {
            dd = rs.getDouble(this.getSqlIndex());
        }
        retVal = new Double(dd);
        break;
    case Types.FLOAT:
        float f = 0;
        if (this.getSqlIndex() == 0) {
            f = rs.getFloat(this.getSqlName());
        } else {
            f = rs.getFloat(this.getSqlIndex());
        }
        retVal = new Float(f);
        break;
    case Types.NUMERIC:
        BigDecimal bd = null;
        if (this.getSqlIndex() == 0) {
            bd = rs.getBigDecimal(this.getSqlName());
        } else {
            bd = rs.getBigDecimal(this.getSqlIndex());
        }
        retVal = bd;
        break;
    case Types.TIMESTAMP:
        Timestamp ts = null;
        if (this.getSqlIndex() == 0) {
            ts = rs.getTimestamp(this.getSqlName());
        } else {
            ts = rs.getTimestamp(this.getSqlIndex());
        }
        retVal = ts;
        break;
    default:
        if (this.getSqlIndex() == 0) {
            retVal = rs.getObject(this.getSqlName());
        } else {
            retVal = rs.getObject(this.getSqlIndex());
        }
        break;
    }
    if (log.isDebugEnabled()) {
        log.debug(this.getAttribute() + "=" + retVal);
    }
    return retVal;
}

From source file:org.apache.ddlutils.io.RoundtripTestBase.java

/**
 * Returns the original model adjusted for type changes because of the native type mappings
 * which when read back from the database will map to different types.
 * /* ww  w  . ja  va2  s  .  c o m*/
 * @return The adjusted model
 */
protected Database getAdjustedModel() {
    try {
        Database model = (Database) getModel().clone();

        for (int tableIdx = 0; tableIdx < model.getTableCount(); tableIdx++) {
            Table table = model.getTable(tableIdx);

            for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++) {
                Column column = table.getColumn(columnIdx);
                int origType = column.getTypeCode();
                int targetType = getPlatformInfo().getTargetJdbcType(origType);

                // we adjust the column types if the native type would back-map to a
                // different jdbc type
                if (targetType != origType) {
                    column.setTypeCode(targetType);
                    // we should also adapt the default value
                    if (column.getDefaultValue() != null) {
                        DefaultValueHelper helper = getPlatform().getSqlBuilder().getDefaultValueHelper();

                        column.setDefaultValue(helper.convert(column.getDefaultValue(), origType, targetType));
                    }
                }
                // we also promote the default size if the column has no size
                // spec of its own
                if ((column.getSize() == null) && getPlatformInfo().hasSize(targetType)) {
                    Integer defaultSize = getPlatformInfo().getDefaultSize(targetType);

                    if (defaultSize != null) {
                        column.setSize(defaultSize.toString());
                    }
                }
                // finally the platform might return a synthetic default value if the column
                // is a primary key column
                if (getPlatformInfo().isSyntheticDefaultValueForRequiredReturned()
                        && (column.getDefaultValue() == null) && column.isRequired()
                        && !column.isAutoIncrement()) {
                    switch (column.getTypeCode()) {
                    case Types.TINYINT:
                    case Types.SMALLINT:
                    case Types.INTEGER:
                    case Types.BIGINT:
                        column.setDefaultValue("0");
                        break;
                    case Types.REAL:
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        column.setDefaultValue("0.0");
                        break;
                    case Types.BIT:
                        column.setDefaultValue("false");
                        break;
                    default:
                        column.setDefaultValue("");
                        break;
                    }
                }
            }
            // we also add the default names to foreign keys that are initially unnamed
            for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++) {
                ForeignKey fk = table.getForeignKey(fkIdx);

                if (fk.getName() == null) {
                    fk.setName(getPlatform().getSqlBuilder().getForeignKeyName(table, fk));
                }
            }
        }
        return model;
    } catch (CloneNotSupportedException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.liferay.portal.upgrade.util.Table.java

public Object getValue(ResultSet rs, String name, Integer type) throws Exception {

    Object value = null;//from w  ww.ja va 2s  . co m

    int t = type.intValue();

    if (t == Types.BIGINT) {
        try {
            value = GetterUtil.getLong(rs.getLong(name));
        } catch (SQLException e) {
            value = GetterUtil.getLong(rs.getString(name));
        }
    } else if (t == Types.BOOLEAN) {
        value = GetterUtil.getBoolean(rs.getBoolean(name));
    } else if (t == Types.CLOB) {
        try {
            Clob clob = rs.getClob(name);

            if (clob == null) {
                value = StringPool.BLANK;
            } else {
                UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(clob.getCharacterStream());

                StringBundler sb = new StringBundler();

                String line = null;

                while ((line = unsyncBufferedReader.readLine()) != null) {
                    if (sb.length() != 0) {
                        sb.append(SAFE_NEWLINE_CHARACTER);
                    }

                    sb.append(line);
                }

                value = sb.toString();
            }
        } catch (Exception e) {

            // If the database doesn't allow CLOB types for the column
            // value, then try retrieving it as a String

            value = GetterUtil.getString(rs.getString(name));
        }
    } else if (t == Types.DOUBLE) {
        value = GetterUtil.getDouble(rs.getDouble(name));
    } else if (t == Types.FLOAT) {
        value = GetterUtil.getFloat(rs.getFloat(name));
    } else if (t == Types.INTEGER) {
        value = GetterUtil.getInteger(rs.getInt(name));
    } else if (t == Types.SMALLINT) {
        value = GetterUtil.getShort(rs.getShort(name));
    } else if (t == Types.TIMESTAMP) {
        try {
            value = rs.getTimestamp(name);
        } catch (Exception e) {
        }

        if (value == null) {
            value = StringPool.NULL;
        }
    } else if (t == Types.VARCHAR) {
        value = GetterUtil.getString(rs.getString(name));
    } else {
        throw new UpgradeException("Upgrade code using unsupported class type " + type);
    }

    return value;
}