List of usage examples for java.sql PreparedStatement setDate
void setDate(int parameterIndex, java.sql.Date x) throws SQLException;
java.sql.Date
value using the default time zone of the virtual machine that is running the application. From source file:com.cedarsoftware.ncube.NCubeManager.java
/** * Update the passed in NCube. Only SNAPSHOT ncubes can be updated. * * @param connection JDBC connection// ww w. ja v a 2 s. com * @param ncube NCube to be updated. * @return boolean true on success, false otherwise */ public static boolean updateCube(Connection connection, String app, NCube ncube, String version) { validate(connection, app, version); if (ncube == null) { throw new IllegalArgumentException("NCube cannot be null for updating"); } synchronized (cubeList) { PreparedStatement stmt = null; try { stmt = connection.prepareStatement( "UPDATE n_cube SET cube_value_bin=?, update_dt=? WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ? AND status_cd = '" + ReleaseStatus.SNAPSHOT + "'"); stmt.setBytes(1, new JsonFormatter().format(ncube).getBytes("UTF-8")); stmt.setDate(2, new java.sql.Date(System.currentTimeMillis())); stmt.setString(3, app); stmt.setString(4, ncube.getName()); stmt.setString(5, version); int count = stmt.executeUpdate(); if (count != 1) { throw new IllegalStateException("Only one (1) row should be updated."); } ncube.setVersion(version); return true; } catch (IllegalStateException e) { throw e; } catch (Exception e) { String s = "Unable to update NCube: " + ncube.getName() + ", app: " + app + ", version: " + version; LOG.error(s, e); throw new RuntimeException(s, e); } finally { jdbcCleanup(stmt); } } }
From source file:com.cedarsoftware.ncube.NCubeManager.java
/** * Update the test data associated to an NCube * * @return true if the update succeeds, false otherwise *//*from w w w. j a v a2 s . c om*/ public static boolean updateTestData(Connection connection, String app, String name, String version, String testData) { validate(connection, app, version); validateCubeName(name); synchronized (cubeList) { PreparedStatement stmt = null; try { stmt = connection.prepareStatement( "UPDATE n_cube SET test_data_bin=?, update_dt=? WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ? AND status_cd = '" + ReleaseStatus.SNAPSHOT + "'"); stmt.setBytes(1, testData == null ? null : testData.getBytes("UTF-8")); stmt.setDate(2, new java.sql.Date(System.currentTimeMillis())); stmt.setString(3, app); stmt.setString(4, name); stmt.setString(5, version); int count = stmt.executeUpdate(); if (count > 1) { throw new IllegalStateException("Only one (1) row's test data should be updated."); } if (count == 0) { throw new IllegalStateException( "No NCube matching app: " + app + ", name: " + name + ", version: " + version); } return true; } catch (IllegalStateException e) { throw e; } catch (Exception e) { String s = "Unable to update test data for NCube: " + name + ", app: " + app + ", version: " + version; LOG.error(s, e); throw new RuntimeException(s, e); } finally { jdbcCleanup(stmt); } } }
From source file:org.hxzon.util.db.springjdbc.StatementCreatorUtils.java
private static void setValue(PreparedStatement ps, int paramIndex, int sqlType, String typeName, Integer scale, Object inValue) throws SQLException { if (inValue instanceof SqlTypeValue) { ((SqlTypeValue) inValue).setTypeValue(ps, paramIndex, sqlType, typeName); } else if (inValue instanceof SqlValue) { ((SqlValue) inValue).setValue(ps, paramIndex); } else if (sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR || (sqlType == Types.CLOB && isStringValue(inValue.getClass()))) { ps.setString(paramIndex, inValue.toString()); } else if (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) { if (inValue instanceof BigDecimal) { ps.setBigDecimal(paramIndex, (BigDecimal) inValue); } else if (scale != null) { ps.setObject(paramIndex, inValue, sqlType, scale); } else {// w w w. j a v a 2s . c om ps.setObject(paramIndex, inValue, sqlType); } } else if (sqlType == Types.DATE) { if (inValue instanceof java.util.Date) { if (inValue instanceof java.sql.Date) { ps.setDate(paramIndex, (java.sql.Date) inValue); } else { ps.setDate(paramIndex, new java.sql.Date(((java.util.Date) inValue).getTime())); } } else if (inValue instanceof Calendar) { Calendar cal = (Calendar) inValue; ps.setDate(paramIndex, new java.sql.Date(cal.getTime().getTime()), cal); } else { ps.setObject(paramIndex, inValue, Types.DATE); } } else if (sqlType == Types.TIME) { if (inValue instanceof java.util.Date) { if (inValue instanceof java.sql.Time) { ps.setTime(paramIndex, (java.sql.Time) inValue); } else { ps.setTime(paramIndex, new java.sql.Time(((java.util.Date) inValue).getTime())); } } else if (inValue instanceof Calendar) { Calendar cal = (Calendar) inValue; ps.setTime(paramIndex, new java.sql.Time(cal.getTime().getTime()), cal); } else { ps.setObject(paramIndex, inValue, Types.TIME); } } else if (sqlType == Types.TIMESTAMP) { if (inValue instanceof java.util.Date) { if (inValue instanceof java.sql.Timestamp) { ps.setTimestamp(paramIndex, (java.sql.Timestamp) inValue); } else { ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime())); } } else if (inValue instanceof Calendar) { Calendar cal = (Calendar) inValue; ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal); } else { ps.setObject(paramIndex, inValue, Types.TIMESTAMP); } } else if (sqlType == SqlTypeValue.TYPE_UNKNOWN) { if (isStringValue(inValue.getClass())) { ps.setString(paramIndex, inValue.toString()); } else if (isDateValue(inValue.getClass())) { ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime())); } else if (inValue instanceof Calendar) { Calendar cal = (Calendar) inValue; ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal); } else { // Fall back to generic setObject call without SQL type specified. ps.setObject(paramIndex, inValue); } } else { // Fall back to generic setObject call with SQL type specified. ps.setObject(paramIndex, inValue, sqlType); } }
From source file:net.freechoice.model.orm.Map_Profile.java
@Override public PreparedStatementCreator createInsert(final FC_Profile prof) { return new PreparedStatementCreator() { @Override//from w w w. j ava 2 s . c om public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement("insert into FC_Profile(" + " id_user_, " + " site_personal," + " name_first, name_last," + " contact_public, " + " gender, date_birth)" + " values( " + prof.id_user_ + ", ?, ?, ?, ?, ?, ?)", RET_ID); ps.setString(1, prof.site_personal); ps.setString(2, prof.name_first); ps.setString(3, prof.name_last); ps.setString(4, prof.contact_public); ps.setBoolean(5, prof.gender); ps.setDate(6, prof.date_birth); return ps; } }; }
From source file:com.seajas.search.utilities.logging.SearchLogger.java
/** * Default constructor.// w w w . j a v a 2 s . com * * @param name * @param level * @param dataSource * @param loggingDAO */ public SearchLogger(final String name, final String level, final BasicDataSource dataSource, final LoggingDAO loggingDAO) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); // Create the actual logger Logger logger = (Logger) LoggerFactory.getLogger(name); logger.setLevel(Level.toLevel(level)); logger.setAdditive(true); // Create the logging appender AppenderBase<ILoggingEvent> appender = new AppenderBase<ILoggingEvent>() { @Override protected void append(final ILoggingEvent event) { Connection connection = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(JDBC_INSERT); statement.setString(1, event.getLevel().toString()); statement.setString(2, event.getFormattedMessage()); statement.setDate(3, new Date(event.getTimeStamp())); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }; appender.setContext(loggerContext); appender.start(); // Make this the definitive logger logger.addAppender(appender); this.logger = logger; }
From source file:com.cedarsoftware.ncube.NCubeManager.java
/** * Return an array [] of Strings containing all unique App names. *///from w w w . j a v a2 s .c om public static Object[] getAppVersions(Connection connection, String app, String status, Date sysDate) { validateConnection(connection); validateApp(app); validateStatus(status); if (sysDate == null) { sysDate = new Date(); } PreparedStatement stmt = null; try { java.sql.Date systemDate = new java.sql.Date(sysDate.getTime()); stmt = connection.prepareStatement( "SELECT DISTINCT version_no_cd FROM n_cube WHERE app_cd = ? and status_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?)"); stmt.setString(1, app); stmt.setString(2, status); stmt.setDate(3, systemDate); stmt.setDate(4, systemDate); ResultSet rs = stmt.executeQuery(); List<String> records = new ArrayList<String>(); while (rs.next()) { records.add(rs.getString(1)); } Collections.sort(records); // May need to enhance to ensure 2.19.1 comes after 2.2.1 return records.toArray(); } catch (Exception e) { String s = "Unable to fetch all ncube app versions from database"; LOG.error(s, e); throw new RuntimeException(s, e); } finally { jdbcCleanup(stmt); } }
From source file:oscar.util.SqlUtils.java
/** * this utility-method assigns a particular value to a place holder of a PreparedStatement. it tries to find the correct setXxx() value, accoring to the field-type information * represented by "fieldType". quality: this method is bloody alpha (as you migth see :=) */// ww w. jav a 2 s . c o m public static void fillPreparedStatement(PreparedStatement ps, int col, Object val, int fieldType) throws SQLException { try { logger.info("fillPreparedStatement( ps, " + col + ", " + val + ", " + fieldType + ")..."); Object value = null; // Check for hard-coded NULL if (!("$null$".equals(val))) { value = val; } if (value != null) { switch (fieldType) { case FieldTypes.INTEGER: ps.setInt(col, Integer.parseInt((String) value)); break; case FieldTypes.NUMERIC: ps.setBigDecimal(col, createAppropriateNumeric(value)); break; case FieldTypes.CHAR: ps.setString(col, (String) value); break; case FieldTypes.DATE: ps.setDate(col, createAppropriateDate(value)); break; // #checkme case FieldTypes.TIMESTAMP: ps.setTimestamp(col, java.sql.Timestamp.valueOf((String) value)); break; case FieldTypes.DOUBLE: ps.setDouble(col, Double.valueOf((String) value).doubleValue()); break; case FieldTypes.FLOAT: ps.setFloat(col, Float.valueOf((String) value).floatValue()); break; case FieldTypes.LONG: ps.setLong(col, Long.parseLong(String.valueOf(value))); break; case FieldTypes.BLOB: FileHolder fileHolder = (FileHolder) value; try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(fileHolder); out.flush(); byte[] buf = byteOut.toByteArray(); byteOut.close(); out.close(); ByteArrayInputStream bytein = new ByteArrayInputStream(buf); int byteLength = buf.length; ps.setBinaryStream(col, bytein, byteLength); // store fileHolder as a whole (this way we don't lose file meta-info!) } catch (IOException ioe) { MiscUtils.getLogger().error("Error", ioe); logger.info(ioe.toString()); throw new SQLException("error storing BLOB in database - " + ioe.toString(), null, 2); } break; case FieldTypes.DISKBLOB: ps.setString(col, (String) value); break; default: ps.setObject(col, value); // #checkme } } else { switch (fieldType) { case FieldTypes.INTEGER: ps.setNull(col, java.sql.Types.INTEGER); break; case FieldTypes.NUMERIC: ps.setNull(col, java.sql.Types.NUMERIC); break; case FieldTypes.CHAR: ps.setNull(col, java.sql.Types.CHAR); break; case FieldTypes.DATE: ps.setNull(col, java.sql.Types.DATE); break; case FieldTypes.TIMESTAMP: ps.setNull(col, java.sql.Types.TIMESTAMP); break; case FieldTypes.DOUBLE: ps.setNull(col, java.sql.Types.DOUBLE); break; case FieldTypes.FLOAT: ps.setNull(col, java.sql.Types.FLOAT); break; case FieldTypes.BLOB: ps.setNull(col, java.sql.Types.BLOB); case FieldTypes.DISKBLOB: ps.setNull(col, java.sql.Types.CHAR); default: ps.setNull(col, java.sql.Types.OTHER); } } } catch (Exception e) { throw new SQLException("Field type seems to be incorrect - " + e.toString(), null, 1); } }
From source file:netflow.DatabaseProxy.java
private boolean aggregationAlreadyStored(AggregationRecord record) throws SQLException { String query = getQuery("aggregation.record.exists"); PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, record.getClientId());/*ww w . ja v a 2s. com*/ ps.setDate(2, record.getDate()); return doWithStatement(ps, new ResultSetProcessor<Boolean>() { @Override public Boolean process(ResultSet rs) throws SQLException { return rs.first(); } }); }
From source file:cz.muni.fi.javaseminar.kafa.bookregister.AuthorManagerImpl.java
@Override @Transactional(readOnly = false)/*w ww . j a va 2 s .co m*/ public void createAuthor(Author author) { validate(author); if (author.getId() != null) { throw new IllegalArgumentException("author id is already set"); } KeyHolder keyHolder = new GeneratedKeyHolder(); int updated = jdbcTemplate.update((Connection connection) -> { PreparedStatement ps = connection.prepareStatement( "INSERT INTO AUTHOR (firstname,surname,description,nationality,dateofbirth) VALUES (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); ps.setString(1, author.getFirstname()); ps.setString(2, author.getSurname()); ps.setString(3, author.getDescription()); ps.setString(4, author.getNationality()); Date date = Date.valueOf(author.getDateOfBirth()); ps.setDate(5, date); return ps; }, keyHolder); author.setId(keyHolder.getKey().longValue()); DBUtils.checkUpdatesCount(updated, author, true); }
From source file:org.apache.phoenix.end2end.QueryMoreIT.java
private Map<String, List<String>> createHistoryTableRows(String dataTableName, String[] tenantIds, int numRowsPerTenant) throws Exception { String upsertDML = "UPSERT INTO " + dataTableName + " VALUES (?, ?, ?, ?, ?, ?, ?)"; Connection conn = DriverManager.getConnection(getUrl()); Map<String, List<String>> historyIdsForTenant = new HashMap<String, List<String>>(); try {/* w w w . j av a 2 s . c om*/ PreparedStatement stmt = conn.prepareStatement(upsertDML); for (int j = 0; j < tenantIds.length; j++) { List<String> parentIds = new ArrayList<String>(); for (int i = 0; i < numRowsPerTenant; i++) { stmt.setString(1, tenantIds[j]); stmt.setString(2, rightPad("parentId", 15, 'p')); stmt.setDate(3, new Date(100)); String historyId = rightPad("history" + i, 15, 'h'); stmt.setString(4, historyId); stmt.setString(5, "datatype"); stmt.setString(6, "oldval"); stmt.setString(7, "newval"); stmt.executeUpdate(); parentIds.add(historyId); } historyIdsForTenant.put(tenantIds[j], parentIds); } conn.commit(); return historyIdsForTenant; } finally { conn.close(); } }