Example usage for java.sql Types BIT

List of usage examples for java.sql Types BIT

Introduction

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

Prototype

int BIT

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

Click Source Link

Document

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

Usage

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Set Value into PreparedStatement/*from ww w.  j a  v a  2s  .  com*/
 * 
 * @param ps
 * @param value
 * @param rank
 *            >= 1
 * @throws WaarpDatabaseSqlException
 */
static public void setTrueValue(PreparedStatement ps, DbValue value, int rank)
        throws WaarpDatabaseSqlException {
    try {
        switch (value.type) {
        case Types.VARCHAR:
            if (value.value == null) {
                ps.setNull(rank, Types.VARCHAR);
                break;
            }
            ps.setString(rank, (String) value.value);
            break;
        case Types.LONGVARCHAR:
            if (value.value == null) {
                ps.setNull(rank, Types.LONGVARCHAR);
                break;
            }
            ps.setString(rank, (String) value.value);
            break;
        case Types.BIT:
            if (value.value == null) {
                ps.setNull(rank, Types.BIT);
                break;
            }
            ps.setBoolean(rank, (Boolean) value.value);
            break;
        case Types.TINYINT:
            if (value.value == null) {
                ps.setNull(rank, Types.TINYINT);
                break;
            }
            ps.setByte(rank, (Byte) value.value);
            break;
        case Types.SMALLINT:
            if (value.value == null) {
                ps.setNull(rank, Types.SMALLINT);
                break;
            }
            ps.setShort(rank, (Short) value.value);
            break;
        case Types.INTEGER:
            if (value.value == null) {
                ps.setNull(rank, Types.INTEGER);
                break;
            }
            ps.setInt(rank, (Integer) value.value);
            break;
        case Types.BIGINT:
            if (value.value == null) {
                ps.setNull(rank, Types.BIGINT);
                break;
            }
            ps.setLong(rank, (Long) value.value);
            break;
        case Types.REAL:
            if (value.value == null) {
                ps.setNull(rank, Types.REAL);
                break;
            }
            ps.setFloat(rank, (Float) value.value);
            break;
        case Types.DOUBLE:
            if (value.value == null) {
                ps.setNull(rank, Types.DOUBLE);
                break;
            }
            ps.setDouble(rank, (Double) value.value);
            break;
        case Types.VARBINARY:
            if (value.value == null) {
                ps.setNull(rank, Types.VARBINARY);
                break;
            }
            ps.setBytes(rank, (byte[]) value.value);
            break;
        case Types.DATE:
            if (value.value == null) {
                ps.setNull(rank, Types.DATE);
                break;
            }
            ps.setDate(rank, (Date) value.value);
            break;
        case Types.TIMESTAMP:
            if (value.value == null) {
                ps.setNull(rank, Types.TIMESTAMP);
                break;
            }
            ps.setTimestamp(rank, (Timestamp) value.value);
            break;
        case Types.CLOB:
            if (value.value == null) {
                ps.setNull(rank, Types.CLOB);
                break;
            }
            ps.setClob(rank, (Reader) value.value);
            break;
        case Types.BLOB:
            if (value.value == null) {
                ps.setNull(rank, Types.BLOB);
                break;
            }
            ps.setBlob(rank, (InputStream) value.value);
            break;
        default:
            throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " at " + rank);
        }
    } catch (ClassCastException e) {
        throw new WaarpDatabaseSqlException("Setting values casting error: " + value.type + " at " + rank, e);
    } catch (SQLException e) {
        DbSession.error(e);
        throw new WaarpDatabaseSqlException("Setting values in error: " + value.type + " at " + rank, e);
    }
}

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./* w  w w.j av a 2 s  . c  o  m*/
 *
 * 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.apache.openjpa.jdbc.sql.HSQLDictionary.java

@Override
public Column[] getColumns(DatabaseMetaData meta, DBIdentifier catalog, DBIdentifier schemaName,
        DBIdentifier tableName, DBIdentifier columnName, Connection conn) throws SQLException {
    Column[] cols = super.getColumns(meta, catalog, schemaName, tableName, columnName, conn);

    for (int i = 0; cols != null && i < cols.length; i++)
        if ("BOOLEAN".equalsIgnoreCase(cols[i].getTypeIdentifier().getName()))
            cols[i].setType(Types.BIT);
    return cols;/*from  w w  w. j  av  a 2  s .  c om*/
}

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

/**
 * Dump a generic table to XML//from   ww  w.  j av  a 2 s .  c o m
 *
 * @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.castor.jdo.engine.SQLTypeInfos.java

/**
 * Get value from given ResultSet at given index with given SQL type.
 * /* w  w w  .j  a v a2s  . c  o m*/
 * @param rs The ResultSet to get the value from.
 * @param index The index of the value in the ResultSet.
 * @param sqlType The SQL type of the value.
 * @return The value.
 * @throws SQLException If a database access error occurs.
 */
public static Object getValue(final ResultSet rs, final int index, final int sqlType) throws SQLException {
    switch (sqlType) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        return rs.getString(index);
    case Types.DECIMAL:
    case Types.NUMERIC:
        return rs.getBigDecimal(index);
    case Types.INTEGER:
        int intVal = rs.getInt(index);
        return (rs.wasNull() ? null : new Integer(intVal));
    case Types.TIME:
        return rs.getTime(index, getCalendar());
    case Types.DATE:
        return rs.getDate(index);
    case Types.TIMESTAMP:
        return rs.getTimestamp(index, getCalendar());
    case Types.FLOAT:
    case Types.DOUBLE:
        double doubleVal = rs.getDouble(index);
        return (rs.wasNull() ? null : new Double(doubleVal));
    case Types.REAL:
        float floatVal = rs.getFloat(index);
        return (rs.wasNull() ? null : new Float(floatVal));
    case Types.SMALLINT:
        short shortVal = rs.getShort(index);
        return (rs.wasNull() ? null : new Short(shortVal));
    case Types.TINYINT:
        byte byteVal = rs.getByte(index);
        return (rs.wasNull() ? null : new Byte(byteVal));
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
    case Types.BINARY:
        return rs.getBytes(index);
    case Types.BLOB:
        Blob blob = rs.getBlob(index);
        return (blob == null ? null : blob.getBinaryStream());
    case Types.CLOB:
        return rs.getClob(index);
    case Types.BIGINT:
        long longVal = rs.getLong(index);
        return (rs.wasNull() ? null : new Long(longVal));
    case Types.BIT:
        boolean boolVal = rs.getBoolean(index);
        return (rs.wasNull() ? null : new Boolean(boolVal));
    default:
        Object value = rs.getObject(index);
        return (rs.wasNull() ? null : value);
    }
}

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.
 * /*from   w  w  w.  jav a2 s  .co  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:org.hibernate.dialect.Dialect.java

protected Dialect() {
    log.info("Using dialect: " + this);
    sqlFunctions.putAll(STANDARD_AGGREGATE_FUNCTIONS);

    // standard sql92 functions (can be overridden by subclasses)
    registerFunction("substring", new SQLFunctionTemplate(Hibernate.STRING, "substring(?1, ?2, ?3)"));
    registerFunction("locate", new SQLFunctionTemplate(Hibernate.INTEGER, "locate(?1, ?2, ?3)"));
    registerFunction("trim", new SQLFunctionTemplate(Hibernate.STRING, "trim(?1 ?2 ?3 ?4)"));
    registerFunction("length", new StandardSQLFunction("length", Hibernate.INTEGER));
    registerFunction("bit_length", new StandardSQLFunction("bit_length", Hibernate.INTEGER));
    registerFunction("coalesce", new StandardSQLFunction("coalesce"));
    registerFunction("nullif", new StandardSQLFunction("nullif"));
    registerFunction("abs", new StandardSQLFunction("abs"));
    registerFunction("mod", new StandardSQLFunction("mod", Hibernate.INTEGER));
    registerFunction("sqrt", new StandardSQLFunction("sqrt", Hibernate.DOUBLE));
    registerFunction("upper", new StandardSQLFunction("upper"));
    registerFunction("lower", new StandardSQLFunction("lower"));
    registerFunction("cast", new CastFunction());
    registerFunction("extract", new SQLFunctionTemplate(Hibernate.INTEGER, "extract(?1 ?2 ?3)"));

    //map second/minute/hour/day/month/year to ANSI extract(), override on subclasses
    registerFunction("second", new SQLFunctionTemplate(Hibernate.INTEGER, "extract(second from ?1)"));
    registerFunction("minute", new SQLFunctionTemplate(Hibernate.INTEGER, "extract(minute from ?1)"));
    registerFunction("hour", new SQLFunctionTemplate(Hibernate.INTEGER, "extract(hour from ?1)"));
    registerFunction("day", new SQLFunctionTemplate(Hibernate.INTEGER, "extract(day from ?1)"));
    registerFunction("month", new SQLFunctionTemplate(Hibernate.INTEGER, "extract(month from ?1)"));
    registerFunction("year", new SQLFunctionTemplate(Hibernate.INTEGER, "extract(year from ?1)"));

    registerFunction("str", new SQLFunctionTemplate(Hibernate.STRING, "cast(?1 as char)"));

    // register hibernate types for default use in scalar sqlquery type auto detection
    registerHibernateType(Types.BIGINT, Hibernate.BIG_INTEGER.getName());
    registerHibernateType(Types.BINARY, Hibernate.BINARY.getName());
    registerHibernateType(Types.BIT, Hibernate.BOOLEAN.getName());
    registerHibernateType(Types.CHAR, Hibernate.CHARACTER.getName());
    registerHibernateType(Types.DATE, Hibernate.DATE.getName());
    registerHibernateType(Types.DOUBLE, Hibernate.DOUBLE.getName());
    registerHibernateType(Types.FLOAT, Hibernate.FLOAT.getName());
    registerHibernateType(Types.INTEGER, Hibernate.INTEGER.getName());
    registerHibernateType(Types.SMALLINT, Hibernate.SHORT.getName());
    registerHibernateType(Types.TINYINT, Hibernate.BYTE.getName());
    registerHibernateType(Types.TIME, Hibernate.TIME.getName());
    registerHibernateType(Types.TIMESTAMP, Hibernate.TIMESTAMP.getName());
    registerHibernateType(Types.VARCHAR, Hibernate.STRING.getName());
    registerHibernateType(Types.VARBINARY, Hibernate.BINARY.getName());
    registerHibernateType(Types.NUMERIC, Hibernate.BIG_DECIMAL.getName());
    registerHibernateType(Types.DECIMAL, Hibernate.BIG_DECIMAL.getName());
    registerHibernateType(Types.BLOB, Hibernate.BLOB.getName());
    registerHibernateType(Types.CLOB, Hibernate.CLOB.getName());
    registerHibernateType(Types.REAL, Hibernate.FLOAT.getName());
}

From source file:org.apache.synapse.mediators.db.AbstractDBMediator.java

/**
 * Return a Prepared statement for the given Statement object, which is ready to be executed
 *
 * @param stmnt  SQL stataement to be executed
 * @param con    The connection to be used
 * @param msgCtx Current message context
 * @return a PreparedStatement//w  w  w .j a v  a  2 s  . c  o  m
 * @throws SQLException on error
 */
protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx)
        throws SQLException {

    SynapseLog synLog = getLog(msgCtx);

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Getting a connection from DataSource " + getDSName()
                + " and preparing statement : " + stmnt.getRawStatement());
    }

    if (con == null) {
        String msg = "Connection from DataSource " + getDSName() + " is null.";
        log.error(msg);
        throw new SynapseException(msg);
    }

    if (dataSource instanceof BasicDataSource) {

        BasicDataSource basicDataSource = (BasicDataSource) dataSource;
        int numActive = basicDataSource.getNumActive();
        int numIdle = basicDataSource.getNumIdle();
        String connectionId = Integer.toHexString(con.hashCode());

        DBPoolView dbPoolView = getDbPoolView();
        if (dbPoolView != null) {
            dbPoolView.setNumActive(numActive);
            dbPoolView.setNumIdle(numIdle);
            dbPoolView.updateConnectionUsage(connectionId);
        }

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("[ DB Connection : " + con + " ]");
            synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]");
            synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]");
            synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]");
        }
    }

    PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement());

    // set parameters if any
    List<Statement.Parameter> params = stmnt.getParameters();
    int column = 1;

    for (Statement.Parameter param : params) {
        if (param == null) {
            continue;
        }
        String value = (param.getPropertyName() != null ? param.getPropertyName()
                : param.getXpath().stringValueOf(msgCtx));

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : "
                    + param.getType() + "(see java.sql.Types for valid " + "types)");
        }

        switch (param.getType()) {
        // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR: {
            if (value != null && value.length() != 0) {
                ps.setString(column++, value);
            } else {
                ps.setString(column++, null);
            }
            break;
        }
        case Types.NUMERIC:
        case Types.DECIMAL: {
            if (value != null && value.length() != 0) {
                ps.setBigDecimal(column++, new BigDecimal(value));
            } else {
                ps.setBigDecimal(column++, null);
            }
            break;
        }
        case Types.BIT: {
            if (value != null && value.length() != 0) {
                ps.setBoolean(column++, Boolean.parseBoolean(value));
            } else {
                ps.setNull(column++, Types.BIT);
            }
            break;
        }
        case Types.TINYINT: {
            if (value != null && value.length() != 0) {
                ps.setByte(column++, Byte.parseByte(value));
            } else {
                ps.setNull(column++, Types.TINYINT);
            }
            break;
        }
        case Types.SMALLINT: {
            if (value != null && value.length() != 0) {
                ps.setShort(column++, Short.parseShort(value));
            } else {
                ps.setNull(column++, Types.SMALLINT);
            }
            break;
        }
        case Types.INTEGER: {
            if (value != null && value.length() != 0) {
                ps.setInt(column++, Integer.parseInt(value));
            } else {
                ps.setNull(column++, Types.INTEGER);
            }
            break;
        }
        case Types.BIGINT: {
            if (value != null && value.length() != 0) {
                ps.setLong(column++, Long.parseLong(value));
            } else {
                ps.setNull(column++, Types.BIGINT);
            }
            break;
        }
        case Types.REAL: {
            if (value != null && value.length() != 0) {
                ps.setFloat(column++, Float.parseFloat(value));
            } else {
                ps.setNull(column++, Types.REAL);
            }
            break;
        }
        case Types.FLOAT: {
            if (value != null && value.length() != 0) {
                ps.setDouble(column++, Double.parseDouble(value));
            } else {
                ps.setNull(column++, Types.FLOAT);
            }
            break;
        }
        case Types.DOUBLE: {
            if (value != null && value.length() != 0) {
                ps.setDouble(column++, Double.parseDouble(value));
            } else {
                ps.setNull(column++, Types.DOUBLE);
            }
            break;
        }
        // skip BINARY, VARBINARY and LONGVARBINARY
        case Types.DATE: {
            if (value != null && value.length() != 0) {
                ps.setDate(column++, Date.valueOf(value));
            } else {
                ps.setNull(column++, Types.DATE);
            }
            break;
        }
        case Types.TIME: {
            if (value != null && value.length() != 0) {
                ps.setTime(column++, Time.valueOf(value));
            } else {
                ps.setNull(column++, Types.TIME);
            }
            break;
        }
        case Types.TIMESTAMP: {
            if (value != null && value.length() != 0) {
                ps.setTimestamp(column++, Timestamp.valueOf(value));
            } else {
                ps.setNull(column++, Types.TIMESTAMP);
            }
            break;
        }
        // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT
        default: {
            String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : "
                    + column + " and statement : " + stmnt.getRawStatement()
                    + " used by a DB mediator against DataSource : " + getDSName()
                    + " (see java.sql.Types for valid type values)";
            handleException(msg, msgCtx);
        }
        }
    }

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement()
                + " against DataSource : " + getDSName());
    }
    return ps;
}

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

private String getTypeName(int SQLType) {
    switch (SQLType) {
    case Types.ARRAY:
        return "ARRAY";
    case Types.BIGINT:
        return "INTEGER";
    case Types.BINARY:
        return "BINARY";
    case Types.BIT:
        return "BIT";
    case Types.BLOB:
        return "BLOB";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.CHAR:
        return "CHAR";
    case Types.CLOB:
        return "CLOB";
    case Types.DATALINK:
        return "DATALINK";
    case Types.DATE:
        return "DATE";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.FLOAT:
        return "FLOAT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.NULL:
        return "UNDEFINED";//
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.OTHER:
        return "UNDEFINED";//
    case Types.REAL:
        return "REAL";
    case Types.REF:
        return "REF";
    case Types.ROWID:
        return "ROWID";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.SQLXML:
        return "SQLXML";
    case Types.STRUCT:
        return "STRUCT";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.TINYINT:
        return "TINYINT";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.VARCHAR:
        return "VARCHAR";
    default:/*from ww w  . ja va  2  s.  co  m*/
        return "UNDEFINED";//
    }
}

From source file:org.jumpmind.symmetric.db.derby.DerbyFunctions.java

public static String getPrimaryKeyWhereString(String[] pkColumnNames, ResultSet rs) throws SQLException {
    final String AND = " and ";
    ResultSetMetaData metaData = rs.getMetaData();
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < pkColumnNames.length; i++) {
        String columnName = pkColumnNames[i];
        int index = findColumnIndex(metaData, columnName);
        int type = metaData.getColumnType(index);
        if (type != Types.BINARY && type != Types.BLOB && type != Types.LONGVARBINARY
                && type != Types.VARBINARY) {
            b.append("\"").append(columnName).append("\"=");
            switch (type) {
            case Types.BIT:
            case Types.TINYINT:
            case Types.SMALLINT:
            case Types.INTEGER:
            case Types.BIGINT:
            case Types.FLOAT:
            case Types.REAL:
            case Types.DOUBLE:
            case Types.NUMERIC:
            case Types.DECIMAL:
            case Types.BOOLEAN:
                b.append(rs.getObject(index));
                break;
            case Types.CHAR:
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                b.append("\"").append(rs.getString(index)).append("\"");
                break;
            case Types.DATE:
            case Types.TIMESTAMP:
                b.append("{ts '");
                b.append(rs.getString(index));
                b.append("'}");
                break;
            }// w  w w.  j av a 2  s  .c om
            b.append(AND);
        }
    }
    b.replace(b.length() - AND.length(), b.length(), "");
    return b.toString();
}