Example usage for java.sql PreparedStatement setByte

List of usage examples for java.sql PreparedStatement setByte

Introduction

In this page you can find the example usage for java.sql PreparedStatement setByte.

Prototype

void setByte(int parameterIndex, byte x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java byte value.

Usage

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

/**
 * Set Value into PreparedStatement/*from ww w  . java 2 s. co  m*/
 * 
 * @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:com.chiralbehaviors.CoRE.kernel.Bootstrap.java

public void insert(WellKnownRelationship wko) throws SQLException {
    PreparedStatement s = connection.prepareStatement(String.format(
            "INSERT into %s (id, name, description, updated_by, inverse, preferred) VALUES (?, ?, ?, ?, ?, ?)",
            wko.tableName()));// w  w  w. ja v a  2s.  c o m
    try {
        s.setString(1, wko.id());
        s.setString(2, wko.wkoName());
        s.setString(3, wko.description());
        s.setString(4, WellKnownAgency.CORE.id());
        s.setString(5, wko.inverse().id());
        s.setByte(6, (byte) (wko.preferred() ? 1 : 0));
        s.execute();
    } catch (SQLException e) {
        throw new SQLException(String.format("Unable to insert %s", wko), e);
    }
}

From source file:org.jobjects.dao.annotation.ManagerTools.java

protected final void setAll(PreparedStatement pstmt, int i, Object obj) throws SQLException {
    if (obj instanceof Boolean) {
        pstmt.setBoolean(i, ((Boolean) obj).booleanValue());
    }/*from w w w  . jav a  2  s.co m*/
    if (obj instanceof Byte) {
        pstmt.setByte(i, ((Byte) obj).byteValue());
    }
    if (obj instanceof Short) {
        pstmt.setShort(i, ((Short) obj).shortValue());
    }
    if (obj instanceof Integer) {
        pstmt.setInt(i, ((Integer) obj).intValue());
    }
    if (obj instanceof Long) {
        pstmt.setLong(i, ((Long) obj).longValue());
    }
    if (obj instanceof Float) {
        pstmt.setFloat(i, ((Float) obj).floatValue());
    }
    if (obj instanceof Double) {
        pstmt.setDouble(i, ((Double) obj).doubleValue());
    }
    if (obj instanceof Timestamp) {
        pstmt.setTimestamp(i, ((Timestamp) obj));
    }
    if (obj instanceof Date) {
        pstmt.setDate(i, ((Date) obj));
    }
    if (obj instanceof BigDecimal) {
        pstmt.setBigDecimal(i, ((BigDecimal) obj));
    }
    if (obj instanceof String) {
        pstmt.setString(i, ((String) obj));
    }
}

From source file:lcn.module.batch.core.item.database.support.MethodMapItemPreparedStatementSetter.java

/**
 * params ? ? sqlType PreparedStatement? ??
 *//*from www  .ja va2s. co  m*/
public void setValues(T item, PreparedStatement ps, String[] params, String[] sqlTypes,
        Map<String, Method> methodMap) throws SQLException {

    ReflectionSupport<T> reflector = new ReflectionSupport<T>();

    for (int i = 0; i < params.length; i++) {
        try {

            if (sqlTypes[i].equals("String")) {
                ps.setString(i + 1, (String) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("int")) {
                ps.setInt(i + 1, (Integer) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("double")) {
                ps.setDouble(i + 1, (Double) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Date")) {
                ps.setDate(i + 1, (Date) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte")) {
                ps.setByte(i + 1, (Byte) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("short")) {
                ps.setShort(i + 1, (Short) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("boolean")) {
                ps.setBoolean(i + 1, (Boolean) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("long")) {
                ps.setLong(i + 1, (Long) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Float")) {
                ps.setFloat(i + 1, (Float) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("BigDecimal")) {
                ps.setBigDecimal(i + 1, (BigDecimal) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte[]")) {
                ps.setBytes(i + 1, (byte[]) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else {
                throw new SQLException();
            }
        } catch (IllegalArgumentException e) {
            ReflectionUtils.handleReflectionException(e);
        }
    }
}

From source file:egovframework.rte.bat.core.item.database.support.EgovMethodMapItemPreparedStatementSetter.java

/**
 * params ? ? sqlType PreparedStatement? ??
 *//*from  www . ja v a 2 s  . c o  m*/
public void setValues(T item, PreparedStatement ps, String[] params, String[] sqlTypes,
        Map<String, Method> methodMap) throws SQLException {

    EgovReflectionSupport<T> reflector = new EgovReflectionSupport<T>();

    for (int i = 0; i < params.length; i++) {
        try {

            if (sqlTypes[i].equals("String")) {
                ps.setString(i + 1, (String) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("int")) {
                ps.setInt(i + 1, (Integer) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("double")) {
                ps.setDouble(i + 1, (Double) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Date")) {
                ps.setDate(i + 1, (Date) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte")) {
                ps.setByte(i + 1, (Byte) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("short")) {
                ps.setShort(i + 1, (Short) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("boolean")) {
                ps.setBoolean(i + 1, (Boolean) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("long")) {
                ps.setLong(i + 1, (Long) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Float")) {
                ps.setFloat(i + 1, (Float) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("BigDecimal")) {
                ps.setBigDecimal(i + 1, (BigDecimal) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte[]")) {
                ps.setBytes(i + 1, (byte[]) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else {
                throw new SQLException();
            }
        } catch (IllegalArgumentException e) {
            ReflectionUtils.handleReflectionException(e);
        }
    }
}

From source file:com.jabyftw.lobstercraft.world.CityStructure.java

/**
 * Create a house for the citizens.<br>
 * Note: this should run asynchronously.
 *
 * @param blockLocation house location given by the city manager
 * @return a response for the CommandSender
 *//*from  w  ww.ja va2 s .co  m*/
public HouseCreationResponse createHouse(@NotNull final BlockLocation blockLocation) throws SQLException {
    // Check if there are more houses than current number of citizens + 1 (if level isn't the maximum)
    if (cityHouses.size() >= getMaximumNumberOfCitizens() + (cityLevel == MAXIMUM_CITY_LEVEL ? 0 : 2))
        return HouseCreationResponse.TOO_MANY_HOUSES_REGISTERED;

    // Check minimum height
    if (blockLocation.getY()
            - BlockProtectionType.CITY_HOUSES.getProtectionDistance() < WorldService.MINIMUM_PROTECTION_HEIGHT)
        return HouseCreationResponse.HOUSE_COORDINATE_Y_TOO_LOW;

    // Check minimum and maximum distance between city center
    // Note: this should use the protection distance of the CITY_BLOCKS because this would make the center on the "same height" as the block if checkY is enabled on
    // CITY_HOUSES but not on CITY_BLOCKS
    // Note: the corner of the house should be the corner of current protection range
    if (BlockProtectionType.CITY_BLOCKS.protectionDistanceSquared(blockLocation,
            centerLocation) < getProtectionRangeSquared()
                    - BlockProtectionType.CITY_HOUSES.getProtectionDistanceSquared())
        return HouseCreationResponse.TOO_FAR_FROM_CENTER;
    else if (BlockProtectionType.CITY_BLOCKS.protectionDistanceSquared(blockLocation,
            centerLocation) < BlockProtectionType.CITY_HOUSES.getProtectionDistanceSquared())
        return HouseCreationResponse.TOO_CLOSE_TO_THE_CENTER;

    // Check minimum distance between other houses
    for (BlockLocation existingBlockLocation : cityHouses.keySet())
        if (BlockProtectionType.CITY_HOUSES.protectionDistanceSquared(blockLocation,
                existingBlockLocation) <= BlockProtectionType.CITY_HOUSES.getProtectionDistanceSquared())
            return HouseCreationResponse.TOO_CLOSE_TO_OTHER_HOUSE;

    int houseId;
    // Insert to database
    {
        Connection connection = LobsterCraft.dataSource.getConnection();
        // Prepare statement
        PreparedStatement preparedStatement = connection.prepareStatement(
                "INSERT INTO `minecraft`.`city_house_locations` (`city_cityId`, `worlds_worldId`, `centerChunkX`, `centerChunkZ`, `centerX`, `centerY`, `centerZ`) "
                        + "VALUES (?, ?, ?, ?, ?, ?, ?);",
                Statement.RETURN_GENERATED_KEYS);

        // Set variables
        preparedStatement.setInt(1, cityId);
        preparedStatement.setByte(2, blockLocation.getChunkLocation().getWorldId());
        preparedStatement.setInt(3, blockLocation.getChunkLocation().getChunkX());
        preparedStatement.setInt(4, blockLocation.getChunkLocation().getChunkZ());
        preparedStatement.setByte(5, blockLocation.getRelativeX());
        preparedStatement.setShort(6, blockLocation.getY());
        preparedStatement.setByte(7, blockLocation.getRelativeZ());

        // Execute statement, get generated key
        preparedStatement.execute();
        ResultSet generatedKeys = preparedStatement.getGeneratedKeys();

        // Check if id exists
        if (!generatedKeys.next())
            throw new SQLException("Generated key not generated!");

        // Get house key
        houseId = generatedKeys.getInt("houseId");
        if (houseId <= 0)
            throw new SQLException("House id must be greater than 0");
    }

    // Create variable
    CityHouse cityHouse = new CityHouse(houseId, cityId, blockLocation);

    // Insert house and return
    cityHouses.put(cityHouse, cityHouse);
    return HouseCreationResponse.SUCCESSFULLY_CREATED_HOUSE;
}

From source file:com.jagornet.dhcp.db.JdbcIaAddressDAO.java

public void create(final IaAddress iaAddr) {
    /**/* ww  w. j  ava2 s .c om*/
     * Note: see https://issues.apache.org/jira/browse/DERBY-3609
     * "Formally, Derby does not support getGeneratedKeys since 
     * DatabaseMetaData.supportsGetGeneratedKeys() returns false. 
     * However, Statement.getGeneratedKeys() is partially implemented,
     * ... since it will only return a meaningful result when an single 
     * row insert is done with INSERT...VALUES"
     * 
     * Spring has thus provided a workaround as described here:
     * http://jira.springframework.org/browse/SPR-5306
     */
    GeneratedKeyHolder newKey = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn.prepareStatement(
                    "insert into iaaddress" + " (ipaddress, starttime, preferredendtime, validendtime,"
                            + " state, identityassoc_id)" + " values (?, ?, ?, ?, ?, ?)",
                    PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setBytes(1, iaAddr.getIpAddress().getAddress());
            java.sql.Timestamp sts = new java.sql.Timestamp(iaAddr.getStartTime().getTime());
            ps.setTimestamp(2, sts, Util.GMT_CALENDAR);
            java.sql.Timestamp pts = new java.sql.Timestamp(iaAddr.getPreferredEndTime().getTime());
            ps.setTimestamp(3, pts, Util.GMT_CALENDAR);
            java.sql.Timestamp vts = new java.sql.Timestamp(iaAddr.getValidEndTime().getTime());
            ps.setTimestamp(4, vts, Util.GMT_CALENDAR);
            ps.setByte(5, iaAddr.getState());
            ps.setLong(6, iaAddr.getIdentityAssocId());
            return ps;
        }
    }, newKey);
    Number newId = newKey.getKey();
    if (newId != null) {
        iaAddr.setId(newId.longValue());
    }
}

From source file:com.jagornet.dhcp.db.JdbcIaPrefixDAO.java

public void create(final IaPrefix iaPrefix) {
    /**//  w  w w.j  ava  2 s. com
     * Note: see https://issues.apache.org/jira/browse/DERBY-3609
     * "Formally, Derby does not support getGeneratedKeys since 
     * DatabaseMetaData.supportsGetGeneratedKeys() returns false. 
     * However, Statement.getGeneratedKeys() is partially implemented,
     * ... since it will only return a meaningful result when an single 
     * row insert is done with INSERT...VALUES"
     * 
     * Spring has thus provided a workaround as described here:
     * http://jira.springframework.org/browse/SPR-5306
     */
    GeneratedKeyHolder newKey = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn.prepareStatement(
                    "insert into iaprefix" + " (prefixaddress, prefixlength, starttime, preferredendtime,"
                            + " validendtime, state, identityassoc_id)" + " values (?, ?, ?, ?, ?, ?, ?)",
                    PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setBytes(1, iaPrefix.getIpAddress().getAddress());
            ps.setInt(2, iaPrefix.getPrefixLength());
            java.sql.Timestamp sts = new java.sql.Timestamp(iaPrefix.getStartTime().getTime());
            ps.setTimestamp(3, sts, Util.GMT_CALENDAR);
            java.sql.Timestamp pts = new java.sql.Timestamp(iaPrefix.getPreferredEndTime().getTime());
            ps.setTimestamp(4, pts, Util.GMT_CALENDAR);
            java.sql.Timestamp vts = new java.sql.Timestamp(iaPrefix.getValidEndTime().getTime());
            ps.setTimestamp(5, vts, Util.GMT_CALENDAR);
            ps.setByte(6, iaPrefix.getState());
            ps.setLong(7, iaPrefix.getIdentityAssocId());
            return ps;
        }
    }, newKey);
    Number newId = newKey.getKey();
    if (newId != null) {
        iaPrefix.setId(newId.longValue());
    }
}

From source file:com.thinkmore.framework.orm.hibernate.SimpleHibernateDao.java

public void setParameters(PreparedStatement ps, int j, Object value) throws SQLException {
    if (value != null) {
        if (value instanceof java.lang.Integer) {
            ps.setInt(j, (Integer) value);
        } else if (value instanceof java.lang.Long) {
            ps.setLong(j, (Long) value);
        } else if (value instanceof java.util.Date) {
            ps.setTimestamp(j, new java.sql.Timestamp(((Date) value).getTime()));
        } else if (value instanceof java.sql.Date) {
            ps.setDate(j, new java.sql.Date(((Date) value).getTime()));
        } else if (value instanceof java.lang.String) {
            ps.setString(j, value.toString());
        } else if (value instanceof java.lang.Double) {
            ps.setDouble(j, (Double) value);
        } else if (value instanceof java.lang.Byte) {
            ps.setByte(j, (Byte) value);
        } else if (value instanceof java.lang.Character) {
            ps.setString(j, value.toString());
        } else if (value instanceof java.lang.Float) {
            ps.setFloat(j, (Float) value);
        } else if (value instanceof java.lang.Boolean) {
            ps.setBoolean(j, (Boolean) value);
        } else if (value instanceof java.lang.Short) {
            ps.setShort(j, (Short) value);
        } else {/*www. j  a va 2s . c o m*/
            ps.setObject(j, value);
        }
    } else {
        ps.setNull(j, Types.NULL);
    }
}

From source file:cz.lbenda.dataman.db.RowDesc.java

@SuppressWarnings("ConstantConditions")
private <T> void putToPS(ColumnDesc columnDesc, T value, PreparedStatement ps, int position)
        throws SQLException {
    if (value == null) {
        ps.setObject(position, null);/* w  w  w  .  j  a v  a 2 s .  c  o m*/
        return;
    }
    BinaryData bd = value instanceof BinaryData ? (BinaryData) value : null;
    switch (columnDesc.getDataType()) {
    case STRING:
        ps.setString(position, (String) value);
        break;
    case BOOLEAN:
        ps.setBoolean(position, (Boolean) value);
        break;
    case TIMESTAMP:
        ps.setTimestamp(position, (Timestamp) value);
        break;
    case DATE:
        ps.setDate(position, (Date) value);
        break;
    case TIME:
        ps.setTime(position, (Time) value);
        break;
    case BYTE:
        ps.setByte(position, (Byte) value);
        break;
    case SHORT:
        ps.setShort(position, (Short) value);
        break;
    case INTEGER:
        ps.setInt(position, (Integer) value);
        break;
    case LONG:
        ps.setLong(position, (Long) value);
        break;
    case FLOAT:
        ps.setFloat(position, (Float) value);
        break;
    case DOUBLE:
        ps.setDouble(position, (Double) value);
        break;
    case DECIMAL:
        ps.setBigDecimal(position, (BigDecimal) value);
        break;
    case UUID:
        ps.setBytes(position, AbstractHelper.uuidToByteArray((UUID) value));
        break;
    case ARRAY:
        throw new UnsupportedOperationException("The saving changes in ARRAY isn't supported.");
        // ps.setArray(position, (Array) value); break; // FIXME the value isn't in type java.sql.Array
    case BYTE_ARRAY:
        if (bd == null || bd.isNull()) {
            ps.setBytes(position, null);
        } else {
            try {
                ps.setBytes(position, IOUtils.toByteArray(bd.getInputStream()));
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
        break;
    case CLOB:
        if (bd == null || bd.isNull()) {
            ps.setNull(position, Types.CLOB);
        } else {
            ps.setClob(position, bd.getReader());
        }
        break;
    case BLOB:
        if (bd == null || bd.isNull()) {
            ps.setNull(position, Types.BLOB);
        } else {
            ps.setBlob(position, bd.getInputStream());
        }
        break;
    case OBJECT:
        ps.setObject(position, value);
    }
}