List of usage examples for java.sql PreparedStatement setShort
void setShort(int parameterIndex, short x) throws SQLException;
short
value. From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java
/** * Insert dhcp lease./* w ww.j a va 2s. com*/ * * @param lease the lease */ protected void insertDhcpLease(final DhcpLease lease) { getJdbcTemplate().update("insert into dhcplease" + " (ipaddress, duid, iatype, iaid, prefixlen, state," + " starttime, preferredendtime, validendtime," + " ia_options, ipaddr_options)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setBytes(1, lease.getIpAddress().getAddress()); ps.setBytes(2, lease.getDuid()); ps.setByte(3, lease.getIatype()); ps.setLong(4, lease.getIaid()); ps.setShort(5, lease.getPrefixLength()); ps.setByte(6, lease.getState()); java.sql.Timestamp sts = new java.sql.Timestamp(lease.getStartTime().getTime()); ps.setTimestamp(7, sts, Util.GMT_CALENDAR); java.sql.Timestamp pts = new java.sql.Timestamp(lease.getPreferredEndTime().getTime()); ps.setTimestamp(8, pts, Util.GMT_CALENDAR); java.sql.Timestamp vts = new java.sql.Timestamp(lease.getValidEndTime().getTime()); ps.setTimestamp(9, vts, Util.GMT_CALENDAR); ps.setBytes(10, encodeOptions(lease.getIaDhcpOptions())); ps.setBytes(11, encodeOptions(lease.getIaAddrDhcpOptions())); } }); }
From source file:com.chenxin.authority.common.logback.DBAppender.java
void bindLoggingEventWithInsertStatement(PreparedStatement stmt, ILoggingEvent event) throws SQLException { stmt.setString(TIMESTMP_INDEX,/* w ww. j av a 2 s . co m*/ DateFormatUtils.format(new Date(event.getTimeStamp()), "yyyy-MM-dd HH:mm:ss")); stmt.setString(FORMATTED_MESSAGE_INDEX, event.getFormattedMessage()); stmt.setString(LOGGER_NAME_INDEX, event.getLoggerName()); stmt.setString(LEVEL_STRING_INDEX, event.getLevel().toString()); stmt.setString(THREAD_NAME_INDEX, event.getThreadName()); stmt.setShort(REFERENCE_FLAG_INDEX, DBHelper.computeReferenceMask(event)); }
From source file:org.athenasource.framework.unidbi.Datatypes.java
/** * Setting the parameter for the given prepared statement. This method will * cast the value to the object expected type (execept BOOLEAN) as * {@linkplain #getClass(int)}.//from w ww . j ava 2 s . c o m * <p>INSERT, UPDATE should always call this method to set parameters before 'WHERE' keyword.</p> * <p><b>Warining</b>: For parameters after 'WHERE' keyword, always remember 'IS NULL' is not equal to '= NULL'.</p> * * @param index * the parameter index * @param value * the value for the parameter, can be <code>null</code>. * @param unidbType * the datatype of the parameter * @throws SQLException * in case of SQL problems or type conversion fails. */ public static void setParameter(PreparedStatement stmt, int index, Object value, int unidbType) throws SQLException { // Derby needs special handling. boolean isDerby = (stmt instanceof DelegatingPreparedStatement) ? ((DelegatingPreparedStatement) stmt).getDelegate().getClass().getName().contains("derby") : stmt.getClass().getName().contains("derby"); if (value == null) { if (isDerby) { if (unidbType == NCHAR) { stmt.setNull(index, Datatypes.getSQLType(CHAR)); } else if (unidbType == NVARCHAR) { stmt.setNull(index, Datatypes.getSQLType(VARCHAR)); } else { stmt.setNull(index, Datatypes.getSQLType(unidbType)); } } else { stmt.setNull(index, Datatypes.getSQLType(unidbType)); } } else { try { switch (unidbType) { case BOOLEAN: stmt.setByte(index, (byte) (((Number) value).intValue() == 1 ? 1 : 0)); break; case TINYINT: stmt.setByte(index, ((Number) value).byteValue()); break; case SMALLINT: stmt.setShort(index, ((Number) value).shortValue()); break; case INTEGER: stmt.setInt(index, ((Number) value).intValue()); break; case BIGINT: stmt.setLong(index, ((Number) value).longValue()); break; case DECIMAL: stmt.setBigDecimal(index, ((BigDecimal) value)); break; case REAL: stmt.setFloat(index, ((Float) value).floatValue()); break; case DOUBLE: stmt.setDouble(index, ((Double) value).doubleValue()); break; case CHAR: stmt.setString(index, (String) value); break; case NCHAR: if (isDerby) { stmt.setString(index, (String) value); } else { stmt.setNString(index, (String) value); } break; case VARCHAR: stmt.setString(index, (String) value); break; case NVARCHAR: if (isDerby) { stmt.setString(index, (String) value); } else { stmt.setNString(index, (String) value); } break; case CLOB: // Clob/NClob can be represented as String without any problem. - Oct 16, 2008. stmt.setString(index, (String) value); // stmt.setClob(index, ((Clob) value)); break; case NCLOB: if (isDerby) { stmt.setString(index, (String) value); } else { stmt.setNString(index, (String) value); // stmt.setNClob(index, ((NClob) value)); } break; case BLOB: stmt.setBlob(index, ((Blob) value)); break; case TIMESTAMP: stmt.setTimestamp(index, ((Timestamp) value)); break; default: throw new IllegalArgumentException("[!NO SUCH UNIDB DATA TYPE: " + unidbType + "]"); } } catch (ClassCastException cce) { throw new SQLException( "Failed to convert " + value + " (" + value.getClass() + ") to " + getName(unidbType)); } } }
From source file:com.wso2telco.dep.reportingservice.dao.TaxDAO.java
/** * Gets the API request times for application. * * @param consumerKey the consumer key//from w ww .j a v a2s . c o m * @param year the year * @param month the month * @param userId the user id * @return the API request times for application * @throws Exception the exception */ public Map<String, List<APIRequestDTO>> getAPIRequestTimesForApplication(String consumerKey, short year, short month, String userId) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet results = null; String sql = "SELECT api_version,total_request_count AS count,STR_TO_DATE(time,'%Y-%m-%d') as date FROM " + ReportingTable.API_REQUEST_SUMMARY + "WHERE consumerKey=? AND userId=? AND month=? AND year=?;"; Map<String, List<APIRequestDTO>> apiRequests = new HashMap<String, List<APIRequestDTO>>(); try { connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = connection.prepareStatement(sql); ps.setString(1, consumerKey); ps.setString(2, userId); ps.setShort(3, month); ps.setShort(4, year); log.debug("SQL (PS) st ---> " + ps.toString()); results = ps.executeQuery(); log.debug("SQL (PS) ed ---> "); while (results.next()) { APIRequestDTO req = new APIRequestDTO(); req.setApiVersion(results.getString("api_version")); req.setRequestCount(results.getInt("count")); req.setDate(results.getDate("date")); if (apiRequests.containsKey(req.getApiVersion())) { apiRequests.get(req.getApiVersion()).add(req); } else { List<APIRequestDTO> list = new ArrayList<APIRequestDTO>(); list.add(req); apiRequests.put(req.getApiVersion(), list); } } } catch (SQLException e) { handleException("Error occurred while getting Request Times for Application", e); } finally { DbUtils.closeAllConnections(ps, connection, results); } return apiRequests; }
From source file:com.wso2telco.dep.reportingservice.dao.TaxDAO.java
/** * Gets the nb api request times for subscription. * * @param year the year/* w w w . jav a 2 s .c o m*/ * @param month the month * @param apiName the api name * @param apiVersion the api version * @param consumerKey the consumer key * @param operation the operation * @param category the category * @param subcategory the subcategory * @return the nb api request times for subscription * @throws Exception the exception */ public Set<APIRequestDTO> getNbAPIRequestTimesForSubscription(short year, short month, String apiName, String apiVersion, String consumerKey, int operation, String category, String subcategory) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet results = null; String sql = "SELECT api_version,response_count AS count,STR_TO_DATE(time,'%Y-%m-%d') as date FROM " + ReportingTable.NB_API_RESPONSE_SUMMARY + " WHERE year=? and month=? and consumerKey=? and " + "api=? and api_version=? and operationType=? and category =? and subcategory=? and responseCode like '2%'"; Set<APIRequestDTO> apiRequests = new HashSet<APIRequestDTO>(); try { connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = connection.prepareStatement(sql); ps.setShort(1, year); ps.setShort(2, month); ps.setString(3, consumerKey); ps.setString(4, apiName); ps.setString(5, apiVersion); ps.setInt(6, operation); ps.setString(7, category); ps.setString(8, subcategory); results = ps.executeQuery(); while (results.next()) { APIRequestDTO req = new APIRequestDTO(); req.setApiVersion(results.getString("api_version")); req.setRequestCount(results.getInt("count")); req.setDate(results.getDate("date")); apiRequests.add(req); } } catch (SQLException e) { handleException("Error occurred while getting Request Times for Subscription", e); } finally { DbUtils.closeAllConnections(ps, connection, results); } return apiRequests; }
From source file:org.ensembl.healthcheck.util.ConnectionBasedSqlTemplateImpl.java
private void bindParamsToPreparedStatement(PreparedStatement st, Object[] arguments) throws SQLException { int i = 0;// ww w . j a v a 2 s . c o m if (arguments != null) { for (Object arg : arguments) { i++; if (arg == null) { st.setNull(i, Types.NULL); } else if (arg instanceof String) { st.setString(i, (String) arg); } else if (arg instanceof Integer) { st.setInt(i, (Integer) arg); } else if (arg instanceof Boolean) { st.setBoolean(i, (Boolean) arg); } else if (arg instanceof Short) { st.setShort(i, (Short) arg); } else if (arg instanceof Date) { st.setTimestamp(i, new java.sql.Timestamp(((Date) arg).getTime())); } else if (arg instanceof java.sql.Date) { st.setDate(i, new java.sql.Date(((Date) arg).getTime())); } else if (arg instanceof Double) { st.setDouble(i, (Double) arg); } else if (arg instanceof Long) { st.setLong(i, (Long) arg); } else if (arg instanceof BigDecimal) { st.setObject(i, arg); } else if (arg instanceof BigInteger) { st.setObject(i, arg); } else { // Object try { ByteArrayOutputStream bytesS = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytesS); out.writeObject(arg); out.close(); byte[] bytes = bytesS.toByteArray(); bytesS.close(); st.setBytes(i, bytes); } catch (IOException e) { throw new SQLException( "Could not serialize object " + arg + " for use in a PreparedStatement "); } } } } }
From source file:org.waarp.common.database.data.AbstractDbData.java
/** * Set Value into PreparedStatement// w w w . j av a 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: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 www .java2s.c o 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:com.wso2telco.dep.reportingservice.dao.TaxDAO.java
/** * Gets the API request times for subscription. * * @param year the year/*from w w w .j a v a2 s . c om*/ * @param month the month * @param apiName the api name * @param apiVersion the api version * @param consumerKey the consumer key * @param operatorId the operator id * @param operation the operation * @param category the category * @param subcategory the subcategory * @return the API request times for subscription * @throws Exception the exception */ public Set<APIRequestDTO> getAPIRequestTimesForSubscription(short year, short month, String apiName, String apiVersion, String consumerKey, String operatorId, int operation, String category, String subcategory) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet results = null; String sql = "SELECT api_version,response_count AS count,STR_TO_DATE(time,'%Y-%m-%d') as date FROM " + HostObjectConstants.SB_RESPONSE_SUMMARY_TABLE + " WHERE consumerKey=? and api=? and api_version=? and operatorId=? and responseCode like '20_' and month=? and year=? and operationType=? and category =? and subcategory=? "; Set<APIRequestDTO> apiRequests = new HashSet<APIRequestDTO>(); try { connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = connection.prepareStatement(sql); ps.setString(1, consumerKey); ps.setString(2, apiName); ps.setString(3, apiVersion); ps.setString(4, operatorId); ps.setShort(5, month); ps.setShort(6, year); ps.setInt(7, operation); ps.setString(8, category); ps.setString(9, subcategory); log.debug("SQL (PS) st ---> " + ps.toString()); results = ps.executeQuery(); log.debug("SQL (PS) ed ---> "); while (results.next()) { APIRequestDTO req = new APIRequestDTO(); req.setApiVersion(results.getString("api_version")); req.setRequestCount(results.getInt("count")); req.setDate(results.getDate("date")); apiRequests.add(req); } } catch (SQLException e) { handleException("Error occurred while getting Request Times for Subscription", e); } finally { DbUtils.closeAllConnections(ps, connection, results); } log.debug("done getAPIRequestTimesForSubscription"); return apiRequests; }
From source file:chh.utils.db.source.common.JdbcClient.java
private void setPreparedStatementParams(PreparedStatement preparedStatement, List<Column> columnList) throws SQLException { int index = 1; for (Column column : columnList) { Class columnJavaType = Util.getJavaType(column.getSqlType()); if (column.getVal() == null) { preparedStatement.setNull(index, column.getSqlType()); } else if (columnJavaType.equals(String.class)) { preparedStatement.setString(index, (String) column.getVal()); } else if (columnJavaType.equals(Integer.class)) { preparedStatement.setInt(index, (Integer) column.getVal()); } else if (columnJavaType.equals(Double.class)) { preparedStatement.setDouble(index, (Double) column.getVal()); } else if (columnJavaType.equals(Float.class)) { preparedStatement.setFloat(index, (Float) column.getVal()); } else if (columnJavaType.equals(Short.class)) { preparedStatement.setShort(index, (Short) column.getVal()); } else if (columnJavaType.equals(Boolean.class)) { preparedStatement.setBoolean(index, (Boolean) column.getVal()); } else if (columnJavaType.equals(byte[].class)) { preparedStatement.setBytes(index, (byte[]) column.getVal()); } else if (columnJavaType.equals(Long.class)) { preparedStatement.setLong(index, (Long) column.getVal()); } else if (columnJavaType.equals(Date.class)) { preparedStatement.setDate(index, (Date) column.getVal()); } else if (columnJavaType.equals(Time.class)) { preparedStatement.setTime(index, (Time) column.getVal()); } else if (columnJavaType.equals(Timestamp.class)) { preparedStatement.setTimestamp(index, (Timestamp) column.getVal()); } else {/*from ww w . j a v a2s . co m*/ throw new RuntimeException( "Unknown type of value " + column.getVal() + " for column " + column.getColumnName()); } ++index; } }