Example usage for java.sql PreparedStatement setShort

List of usage examples for java.sql PreparedStatement setShort

Introduction

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

Prototype

void setShort(int parameterIndex, short x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java short value.

Usage

From source file:org.dspace.storage.rdbms.DatabaseManager.java

/**
 * Iterate over the given parameters and add them to the given prepared statement. 
 * Only a select number of datatypes are supported by the JDBC driver.
 *
 * @param statement/*from w w w.  j av a2  s . c om*/
 *          The unparameterized statement.
 * @param parameters
 *          The parameters to be set on the statement.
 */
protected static void loadParameters(PreparedStatement statement, Object[] parameters) throws SQLException {
    statement.clearParameters();

    int idx = 1;
    for (Object parameter : parameters) {
        if (parameter instanceof String) {
            statement.setString(idx, (String) parameter);
        } else if (parameter instanceof Long) {
            statement.setLong(idx, ((Long) parameter).longValue());
        } else if (parameter instanceof Integer) {
            statement.setInt(idx, ((Integer) parameter).intValue());
        } else if (parameter instanceof Short) {
            statement.setShort(idx, ((Short) parameter).shortValue());
        } else if (parameter instanceof Date) {
            statement.setDate(idx, (Date) parameter);
        } else if (parameter instanceof Time) {
            statement.setTime(idx, (Time) parameter);
        } else if (parameter instanceof Timestamp) {
            statement.setTimestamp(idx, (Timestamp) parameter);
        } else if (parameter instanceof Double) {
            statement.setDouble(idx, ((Double) parameter).doubleValue());
        } else if (parameter instanceof Float) {
            statement.setFloat(idx, ((Float) parameter).floatValue());
        } else if (parameter == null) {
            throw new SQLException("Attempting to insert null value into SQL query.");
        } else {
            throw new SQLException("Attempting to insert unknown datatype (" + parameter.getClass().getName()
                    + ") into SQL statement.");
        }

        idx++;
    }
}

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

/**
 * params ? ? sqlType PreparedStatement? ??
 *//*from  w w  w .ja  v  a  2  s.com*/
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   w ww . j a  v a 2  s.  co  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:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java

private PreparedStatement createPreapredStatementUsingSetXXX(String sql) throws SQLException {
    PreparedStatement ps = con.prepareStatement(sql);

    ps.setBoolean(1, true); //setBoolean
    ps.setBoolean(2, true); //setBoolean

    ps.setShort(3, Short.valueOf("1")); //setShort
    ps.setInt(4, 2); //setInt
    ps.setFloat(5, 3f); //setFloat
    ps.setDouble(6, Double.valueOf(4)); //setDouble
    ps.setString(7, "test'string\""); //setString
    ps.setLong(8, 5L); //setLong
    ps.setByte(9, (byte) 1); //setByte
    ps.setByte(10, (byte) 1); //setByte
    ps.setString(11, "2012-01-01"); //setString

    ps.setMaxRows(2);/*w w w.j a va 2  s.  c om*/
    return ps;
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private void setPreparedValue(final PreparedStatement pstmnt, final int index,
        final StructAttributeReflect attr, Object value, final AbstractEntity entity) throws Exception {
    Class<?> type = attr.Field.getType();
    if (EnumPrimitives.isPrimitiveType(type)) {
        EnumPrimitives prim = EnumPrimitives.type(type);
        switch (prim) {
        case ECharacter:
            pstmnt.setString(index, String.valueOf(value));
            break;
        case EShort:
            pstmnt.setShort(index, (Short) value);
            break;
        case EInteger:
            pstmnt.setInt(index, (Integer) value);
            break;
        case ELong:
            pstmnt.setLong(index, (Long) value);
            break;
        case EFloat:
            pstmnt.setFloat(index, (Float) value);
            break;
        case EDouble:
            pstmnt.setDouble(index, (Double) value);
            break;
        default:/* w  ww  . j a v  a 2s . co  m*/
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else {
        if (type.equals(String.class)) {
            pstmnt.setString(index, (String) value);
        } else if (type.equals(Date.class)) {
            long dtval = new Date().getTime();
            if (value != null) {
                dtval = ((Date) value).getTime();
            }
            pstmnt.setLong(index, dtval);
        } else if (value instanceof Enum) {
            pstmnt.setString(index, getEnumValue(value));
        } else if (attr.Convertor != null) {
            pstmnt.setString(index, (String) attr.Convertor.save(entity, attr.Field.getName()));
        } else if (attr.Reference != null) {
            Class<?> cls = Class.forName(attr.Reference.Class);
            StructAttributeReflect rattr = ReflectionUtils.get().getAttribute(cls, attr.Reference.Field);
            Object refval = PropertyUtils.getSimpleProperty(entity, attr.Field.getName());
            value = PropertyUtils.getSimpleProperty(refval, rattr.Field.getName());
            setPreparedValue(pstmnt, index, rattr, value, entity);
        } else
            throw new Exception("Unsupported field type [" + type.getCanonicalName() + "]");
    }
}

From source file:com.kylinolap.rest.service.QueryService.java

/**
 * @param preparedState/*from  w  w  w  .ja va 2 s  . co  m*/
 * @param param
 * @throws SQLException
 */
private void setParam(PreparedStatement preparedState, int index, StateParam param) throws SQLException {
    boolean isNull = (null == param.getValue());

    Class<?> clazz = Object.class;
    try {
        clazz = Class.forName(param.getClassName());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Rep rep = Rep.of(clazz);

    switch (rep) {
    case PRIMITIVE_CHAR:
    case CHARACTER:
    case STRING:
        preparedState.setString(index, isNull ? null : String.valueOf(param.getValue()));
        break;
    case PRIMITIVE_INT:
    case INTEGER:
        preparedState.setInt(index, isNull ? null : Integer.valueOf(param.getValue()));
        break;
    case PRIMITIVE_SHORT:
    case SHORT:
        preparedState.setShort(index, isNull ? null : Short.valueOf(param.getValue()));
        break;
    case PRIMITIVE_LONG:
    case LONG:
        preparedState.setLong(index, isNull ? null : Long.valueOf(param.getValue()));
        break;
    case PRIMITIVE_FLOAT:
    case FLOAT:
        preparedState.setFloat(index, isNull ? null : Float.valueOf(param.getValue()));
        break;
    case PRIMITIVE_DOUBLE:
    case DOUBLE:
        preparedState.setDouble(index, isNull ? null : Double.valueOf(param.getValue()));
        break;
    case PRIMITIVE_BOOLEAN:
    case BOOLEAN:
        preparedState.setBoolean(index, isNull ? null : Boolean.parseBoolean(param.getValue()));
        break;
    case PRIMITIVE_BYTE:
    case BYTE:
        preparedState.setByte(index, isNull ? null : Byte.valueOf(param.getValue()));
        break;
    case JAVA_UTIL_DATE:
    case JAVA_SQL_DATE:
        preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIME:
        preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIMESTAMP:
        preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue()));
        break;
    default:
        preparedState.setObject(index, isNull ? null : param.getValue());
    }
}

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

private void setValueToStatement(Object o, PreparedStatement pstmt) throws SQLException {
    if (log.isDebugEnabled()) {
        log.debug(this.sqlIndex + "=" + o);
    }/*  ww  w  .j a v  a  2  s .c  o  m*/
    switch (this.sqlType) {
    case Types.VARCHAR:
    case Types.CHAR:
        String s = (String) o;
        pstmt.setString(this.sqlIndex, s);
        break;
    case Types.BOOLEAN:
        if (o != null && o instanceof Boolean) {
            boolean b = ((Boolean) o).booleanValue();
            pstmt.setBoolean(this.sqlIndex, b);
        }
        break;
    case Types.INTEGER:
        if (o != null && o instanceof Integer) {
            int i = ((Integer) o).intValue();
            pstmt.setInt(this.sqlIndex, i);
        }
        break;
    case Types.SMALLINT:
        if (o != null && o instanceof Short) {
            short ss = ((Short) o).shortValue();
            pstmt.setShort(this.sqlIndex, ss);
        }
        break;
    case Types.TINYINT:
        if (o != null && o instanceof Byte) {
            byte bb = ((Byte) o).byteValue();
            pstmt.setByte(this.sqlIndex, bb);
        }
        break;
    case Types.BIGINT:
        if (o != null && o instanceof Long) {
            long l = ((Long) o).longValue();
            pstmt.setLong(this.sqlIndex, l);
        }
        break;
    case Types.DOUBLE:
        if (o != null && o instanceof Double) {
            double dd = ((Double) o).doubleValue();
            pstmt.setDouble(this.sqlIndex, dd);
        }
        break;
    case Types.FLOAT:
        if (o != null && o instanceof Float) {
            float f = ((Float) o).floatValue();
            pstmt.setFloat(this.sqlIndex, f);
        }
        break;
    case Types.NUMERIC:
        if (o != null && o instanceof BigDecimal) {
            BigDecimal bd = (BigDecimal) o;
            pstmt.setBigDecimal(this.sqlIndex, bd);
        }
        break;
    case Types.TIMESTAMP:
        if (o != null && o instanceof Timestamp) {
            Timestamp ts = (Timestamp) o;
            pstmt.setTimestamp(this.sqlIndex, ts);
        }
        break;
    case Types.NULL:
        if (log.isDebugEnabled()) {
            log.debug(this.sqlIndex + " IS NULL");
        }
        pstmt.setNull(this.sqlIndex, Types.NULL);
        break;
    default:
        if (o != null) {
            pstmt.setObject(this.sqlIndex, o);
        }
    }
}

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   ww  w.  j  a  va 2s .c o 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.liferay.portal.upgrade.util.Table.java

public void setColumn(PreparedStatement ps, int index, Integer type, String value) throws Exception {

    int t = type.intValue();

    int paramIndex = index + 1;

    if (t == Types.BIGINT) {
        ps.setLong(paramIndex, GetterUtil.getLong(value));
    } else if (t == Types.BOOLEAN) {
        ps.setBoolean(paramIndex, GetterUtil.getBoolean(value));
    } else if ((t == Types.CLOB) || (t == Types.VARCHAR)) {
        value = StringUtil.replace(value, SAFE_CHARS[1], SAFE_CHARS[0]);

        ps.setString(paramIndex, value);
    } else if (t == Types.DOUBLE) {
        ps.setDouble(paramIndex, GetterUtil.getDouble(value));
    } else if (t == Types.FLOAT) {
        ps.setFloat(paramIndex, GetterUtil.getFloat(value));
    } else if (t == Types.INTEGER) {
        ps.setInt(paramIndex, GetterUtil.getInteger(value));
    } else if (t == Types.SMALLINT) {
        ps.setShort(paramIndex, GetterUtil.getShort(value));
    } else if (t == Types.TIMESTAMP) {
        if (StringPool.NULL.equals(value)) {
            ps.setTimestamp(paramIndex, null);
        } else {//from  www  .  j  a  v  a  2 s.co m
            DateFormat df = DateUtil.getISOFormat();

            ps.setTimestamp(paramIndex, new Timestamp(df.parse(value).getTime()));
        }
    } else {
        throw new UpgradeException("Upgrade code using unsupported class type " + type);
    }
}

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);/* ww w  . j a v  a 2 s  .  co  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);
    }
}