List of usage examples for java.sql PreparedStatement setTimestamp
void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException;
java.sql.Timestamp
value. From source file:com.googlecode.fascinator.portal.HouseKeeper.java
/** * Store a new action in the database and update the action queue. * /* www . ja v a2s .c o m*/ * @param action The User action to store */ private void storeAction(UserAction action) { // Don't store duplicates if (isCurrentAction(action.message)) { return; } // Capture the current time if (action.date == null) { action.date = new Date(); } // Otherwise proceed as normal try { log.debug("Storing action: '{}'", action.message); // Prepare our query PreparedStatement sql = dbConnection().prepareCall( "INSERT INTO " + NOTIFICATIONS_TABLE + " (block, message, datetime) VALUES (?, ?, ?)"); // Run the query sql.setBoolean(1, action.block); sql.setString(2, action.message); sql.setTimestamp(3, new Timestamp(action.date.getTime())); sql.executeUpdate(); close(sql); // Update memory cache syncActionList(); } catch (SQLException ex) { log.error("Error accessing database: ", ex); } }
From source file:com.skycloud.management.portal.admin.sysmanage.dao.impl.UserManageDaoImpl.java
@Override public int saveSelfcaerUserInfo(final TUserBO user) throws SQLException { KeyHolder keyHolder = new GeneratedKeyHolder(); final String sql = "insert into T_SCS_COMPANY_USER(" + "ID,ACCOUNT,PWD," + "DEPT_ID,ROLE_ID,EMAIL," + "POSITION,STATE," + "COMMENT,CHECK_CODE,IS_AUTO_APPROVE,CREATOR_USER_ID," + "CREATE_DT,LASTUPDATE_DT) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; try {//from www .ja v a2s.c om this.getJdbcTemplate().update(new PreparedStatementCreator() { int i = 1; @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setInt(i++, user.getId()); ps.setString(i++, user.getAccount()); ps.setString(i++, user.getPwd()); // ps.setString(i++, user.getName()); ps.setInt(i++, user.getDeptId()); ps.setInt(i++, user.getRoleId()); ps.setString(i++, user.getEmail()); ps.setString(i++, user.getPosition()); ps.setInt(i++, user.getState()); ps.setString(i++, user.getComment()); ps.setString(i++, user.getCheckCode()); ps.setInt(i++, user.getIsAutoApprove()); ps.setInt(i++, user.getCreatorUserId()); ps.setTimestamp(i++, new Timestamp(user.getCreateDt().getTime())); //update by CQ ps.setTimestamp(i++, new Timestamp(user.getLastupdateDt().getTime())); return ps; } }, keyHolder); } catch (Exception e) { throw new SQLException("??" + user.getComment() + " ID" + user.getCreatorUserId() + " " + user.getCreateDt() + " " + e.getMessage()); } return keyHolder.getKey().intValue(); }
From source file:com.skycloud.management.portal.admin.sysmanage.dao.impl.UserManageDaoImpl.java
@Override public int saveSelfcaerUser(final TUserBO user) throws SQLException { KeyHolder keyHolder = new GeneratedKeyHolder(); final String sql = "insert into T_SCS_USER(" + "ID,ACCOUNT,PWD," + "DEPT_ID,ROLE_ID,EMAIL," + "POSITION,STATE," + "COMMENT,CHECK_CODE,IS_AUTO_APPROVE,CREATOR_USER_ID," + "CREATE_DT,LASTUPDATE_DT,COMP_ID,MOBILE) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; try {//from w w w. jav a 2s .com this.getJdbcTemplate().update(new PreparedStatementCreator() { int i = 1; @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setInt(i++, user.getId()); ps.setString(i++, user.getAccount()); ps.setString(i++, user.getPwd()); // ps.setString(i++, user.getName()); ps.setInt(i++, user.getDeptId()); ps.setInt(i++, user.getRoleId()); ps.setString(i++, user.getEmail()); ps.setString(i++, user.getPosition()); ps.setInt(i++, user.getState()); ps.setString(i++, user.getComment()); ps.setString(i++, user.getCheckCode()); ps.setInt(i++, user.getIsAutoApprove()); ps.setInt(i++, user.getCreatorUserId()); ps.setTimestamp(i++, new Timestamp(user.getCreateDt().getTime())); //update by CQ ps.setTimestamp(i++, new Timestamp(user.getLastupdateDt().getTime())); ps.setInt(i++, user.getCompId()); ps.setString(i++, user.getMobile()); return ps; } }, keyHolder); } catch (Exception e) { throw new SQLException("??" + user.getComment() + " ID" + user.getCreatorUserId() + " " + user.getCreateDt() + " " + e.getMessage()); } return keyHolder.getKey().intValue(); }
From source file:org.koiroha.jyro.workers.crawler.Crawler.java
/** * * @param job/* w w w . ja v a 2s. c o m*/ * @return * @throws WorkerException */ @Distribute(name = "crawl", params = { "url", "referer" }) public void crawl(String url, String referer) throws SQLException, JyroException { List<URI> urls = retrieveLink(url); WorkerContext context = getContext(); Connection con = Transaction.getConnection(); con.setAutoCommit(false); PreparedStatement stmt1 = con.prepareStatement( "INSERT INTO jyro_urls(scheme,host,port,path,retrieved_at,created_at) VALUES(?,?,?,?,?,?)"); PreparedStatement stmt = con.prepareStatement( "SELECT EXISTS(SELECT * FROM jyro_urls WHERE scheme=? AND host=? AND port=? AND path=?)"); for (URI uri : urls) { int port = getPort(uri); if (port < 0) { logger.debug(uri + " is not supported"); continue; } stmt.setString(1, uri.getScheme()); stmt.setString(2, uri.getHost()); stmt.setInt(3, port); stmt.setString(4, uri.getPath()); ResultSet rs = stmt.executeQuery(); rs.next(); boolean exists = rs.getBoolean(1); if (!exists) { Timestamp now = new Timestamp(System.currentTimeMillis()); stmt1.setString(1, uri.getScheme()); stmt1.setString(2, uri.getHost()); stmt1.setInt(3, port); stmt1.setString(4, uri.getPath()); stmt1.setTimestamp(5, now); stmt1.setTimestamp(6, now); stmt1.executeUpdate(); con.commit(); context.call("crawl", uri.toString()); } else { logger.info("URL " + uri + " already retrieved"); } } stmt.close(); stmt1.close(); con.commit(); return; }
From source file:se.technipelago.weather.chart.Generator.java
private float getSolarHours(final Timespan period) { PreparedStatement stmt = null; ResultSet result = null;//from w w w.ja v a2 s . co m float f = 0f; init(); try { stmt = conn.prepareStatement( "SELECT COUNT(*) / 6 AS hours FROM archive WHERE solar > 120 AND ts BETWEEN ? AND ?"); stmt.setTimestamp(1, new java.sql.Timestamp(period.getStartTime().getTime())); stmt.setTimestamp(2, new java.sql.Timestamp(period.getEndTime().getTime())); result = stmt.executeQuery(); if (result.next()) { f = result.getFloat(1); } } catch (SQLException ex) { log.log(Level.SEVERE, null, ex); } finally { if (result != null) { try { result.close(); } catch (SQLException ex) { log.log(Level.WARNING, "Failed to close ResultSet", ex); } } if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { log.log(Level.WARNING, "Failed to close select statement", ex); } } } return f; }
From source file:net.agmodel.metbroker.driver.impl.JmaGsmJp.java
/** * get database connection and execute SQL command. * And put the result to Sequence Object * @param seqMap Sequence Map//from w w w .j av a 2 s. c om * @param stationId station id * @param query SQL statement * @param start start date * @param end end date * @param hourly if true, use SIX_HOURS, else ONE_DAY * @throws DriverException something fail. */ private void queryTable(StationDataSetProxy seqMap, String stationId, String query, Date start, Date end, boolean hourly) throws DriverException { Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; java.sql.Timestamp startDate = new java.sql.Timestamp(start.getTime()); java.sql.Timestamp endDate = new java.sql.Timestamp(end.getTime()); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); try { con = dataSource.getConnection(); logger.debug("Connection: " + con.toString()); /* stmt = con.prepareStatement(query); stmt.setInt(1, new Integer(stationId).intValue()); stmt.setTimestamp(2, startDate, cal); stmt.setTimestamp(3, endDate, cal); stmt.setInt(4, new Integer(stationId).intValue()); stmt.setTimestamp(5, startDate, cal); stmt.setTimestamp(6, endDate, cal); */ stmt = con.prepareStatement(query); stmt.setInt(1, new Integer(stationId).intValue()); stmt.setTimestamp(2, startDate); stmt.setTimestamp(3, endDate); stmt.setInt(4, new Integer(stationId).intValue()); stmt.setTimestamp(5, startDate); stmt.setTimestamp(6, endDate); rs = stmt.executeQuery(); logger.debug("ResultSet: " + rs.toString()); AirTemperature tempSequence = null; if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) { tempSequence = (AirTemperature) seqMap.getSequence(MetElement.AIRTEMPERATURE); } Rain rainSequence = null; if (seqMap.containsKey(MetElement.RAIN)) { rainSequence = (Rain) seqMap.getSequence(MetElement.RAIN); } Humidity humiditySequence = null; if (seqMap.containsKey(MetElement.HUMIDITY)) { humiditySequence = (Humidity) seqMap.getSequence(MetElement.HUMIDITY); } Wind windSequence = null; if (seqMap.containsKey(MetElement.WIND)) { windSequence = (Wind) seqMap.getSequence(MetElement.WIND); } while (rs.next()) { java.util.Date recordTime = null; MutableInterval dataInterval = new MutableInterval(); recordTime = rs.getTimestamp("end_date"); if (hourly) { dataInterval.set(Duration.SIX_HOURS, recordTime); } else { dataInterval.set(Duration.ONE_DAY, recordTime); } if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) { float dummy = (float) (rs.getFloat("temperature") - 273.15); if (!rs.wasNull()) { ((AirTempMaxMinMeanImpl) tempSequence).putMeanOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.RAIN)) { float dummy = rs.getFloat("total_preciptasion"); if (!rs.wasNull()) { ((RainImpl) rainSequence).putRainfallOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.HUMIDITY)) { float dummy = rs.getFloat("relative_humidity"); if (!rs.wasNull()) { ((RHImpl) humiditySequence).putRHOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.WIND)) { float u = rs.getFloat("u_wind"); if (!rs.wasNull()) { float v = rs.getFloat("v_wind"); if (!rs.wasNull()) { ((Wind2DImpl) windSequence).putSpeedOverInterval(dataInterval, v, u); } } } } } catch (SQLException s) { s.printStackTrace(); } finally { try { rs.close(); } catch (Exception s) { } try { stmt.close(); } catch (Exception s) { } try { con.close(); } catch (Exception e) { } } }
From source file:net.pms.dlna.DLNAMediaDatabase.java
public synchronized void insertData(String name, long modified, int type, DLNAMediaInfo media) { Connection conn = null;/*from w w w . j a va 2 s .com*/ PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement( "INSERT INTO FILES(FILENAME, MODIFIED, TYPE, DURATION, BITRATE, WIDTH, HEIGHT, SIZE, CODECV, FRAMERATE, ASPECT, ASPECTRATIOCONTAINER, ASPECTRATIOVIDEOTRACK, REFRAMES, AVCLEVEL, BITSPERPIXEL, THUMB, CONTAINER, MODEL, EXPOSURE, ORIENTATION, ISO, MUXINGMODE, FRAMERATEMODE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, name); ps.setTimestamp(2, new Timestamp(modified)); ps.setInt(3, type); if (media != null) { if (media.getDuration() != null) { ps.setDouble(4, media.getDurationInSeconds()); } else { ps.setNull(4, Types.DOUBLE); } int databaseBitrate = 0; if (type != Format.IMAGE) { databaseBitrate = media.getBitrate(); if (databaseBitrate == 0) { logger.debug("Could not parse the bitrate from: " + name); } } ps.setInt(5, databaseBitrate); ps.setInt(6, media.getWidth()); ps.setInt(7, media.getHeight()); ps.setLong(8, media.getSize()); ps.setString(9, left(media.getCodecV(), SIZE_CODECV)); ps.setString(10, left(media.getFrameRate(), SIZE_FRAMERATE)); ps.setString(11, left(media.getAspect(), SIZE_ASPECT)); ps.setString(12, left(media.getAspect(), SIZE_ASPECTRATIO_CONTAINER)); ps.setString(13, left(media.getAspect(), SIZE_ASPECTRATIO_VIDEOTRACK)); ps.setByte(14, media.getReferenceFrameCount()); ps.setString(15, left(media.getAvcLevel(), SIZE_AVC_LEVEL)); ps.setInt(16, media.getBitsPerPixel()); ps.setBytes(17, media.getThumb()); ps.setString(18, left(media.getContainer(), SIZE_CONTAINER)); if (media.getExtras() != null) { ps.setString(19, left(media.getExtrasAsString(), SIZE_MODEL)); } else { ps.setString(19, left(media.getModel(), SIZE_MODEL)); } ps.setInt(20, media.getExposure()); ps.setInt(21, media.getOrientation()); ps.setInt(22, media.getIso()); ps.setString(23, left(media.getMuxingModeAudio(), SIZE_MUXINGMODE)); ps.setString(24, left(media.getFrameRateMode(), SIZE_FRAMERATE_MODE)); } else { ps.setString(4, null); ps.setInt(5, 0); ps.setInt(6, 0); ps.setInt(7, 0); ps.setLong(8, 0); ps.setString(9, null); ps.setString(10, null); ps.setString(11, null); ps.setString(12, null); ps.setString(13, null); ps.setByte(14, (byte) -1); ps.setString(15, null); ps.setInt(16, 0); ps.setBytes(17, null); ps.setString(18, null); ps.setString(19, null); ps.setInt(20, 0); ps.setInt(21, 0); ps.setInt(22, 0); ps.setString(23, null); ps.setString(24, null); } ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); int id = -1; while (rs.next()) { id = rs.getInt(1); } rs.close(); if (media != null && id > -1) { PreparedStatement insert = null; if (media.getAudioTracksList().size() > 0) { insert = conn.prepareStatement( "INSERT INTO AUDIOTRACKS VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); } for (DLNAMediaAudio audio : media.getAudioTracksList()) { insert.clearParameters(); insert.setInt(1, id); insert.setInt(2, audio.getId()); insert.setString(3, left(audio.getLang(), SIZE_LANG)); insert.setString(4, left(audio.getFlavor(), SIZE_FLAVOR)); insert.setInt(5, audio.getAudioProperties().getNumberOfChannels()); insert.setString(6, left(audio.getSampleFrequency(), SIZE_SAMPLEFREQ)); insert.setString(7, left(audio.getCodecA(), SIZE_CODECA)); insert.setInt(8, audio.getBitsperSample()); insert.setString(9, left(trimToEmpty(audio.getAlbum()), SIZE_ALBUM)); insert.setString(10, left(trimToEmpty(audio.getArtist()), SIZE_ARTIST)); insert.setString(11, left(trimToEmpty(audio.getSongname()), SIZE_SONGNAME)); insert.setString(12, left(trimToEmpty(audio.getGenre()), SIZE_GENRE)); insert.setInt(13, audio.getYear()); insert.setInt(14, audio.getTrack()); insert.setInt(15, audio.getAudioProperties().getAudioDelay()); insert.setString(16, left(trimToEmpty(audio.getMuxingModeAudio()), SIZE_MUXINGMODE)); insert.setInt(17, audio.getBitRate()); try { insert.executeUpdate(); } catch (JdbcSQLException e) { if (e.getErrorCode() == 23505) { logger.debug( "A duplicate key error occurred while trying to store the following file's audio information in the database: " + name); } else { logger.debug( "An error occurred while trying to store the following file's audio information in the database: " + name); } logger.debug("The error given by jdbc was: " + e); } } if (media.getSubtitleTracksList().size() > 0) { insert = conn.prepareStatement("INSERT INTO SUBTRACKS VALUES (?, ?, ?, ?, ?)"); } for (DLNAMediaSubtitle sub : media.getSubtitleTracksList()) { if (sub.getExternalFile() == null) { // no save of external subtitles insert.clearParameters(); insert.setInt(1, id); insert.setInt(2, sub.getId()); insert.setString(3, left(sub.getLang(), SIZE_LANG)); insert.setString(4, left(sub.getFlavor(), SIZE_FLAVOR)); insert.setInt(5, sub.getType().getStableIndex()); try { insert.executeUpdate(); } catch (JdbcSQLException e) { if (e.getErrorCode() == 23505) { logger.debug( "A duplicate key error occurred while trying to store the following file's subtitle information in the database: " + name); } else { logger.debug( "An error occurred while trying to store the following file's subtitle information in the database: " + name); } logger.debug("The error given by jdbc was: " + e); } } } close(insert); } } catch (SQLException se) { if (se.getErrorCode() == 23001) { logger.debug("Duplicate key while inserting this entry: " + name + " into the database: " + se.getMessage()); } else { logger.error(null, se); } } finally { close(ps); close(conn); } }
From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java
public Transaction createTransaction(int source_user_id, int destination_user_id, long amount) throws SQLException { Connection connection = getConnection(); PreparedStatement statement = null; PreparedStatement statementAccountS = null; PreparedStatement statementAccountD = null; Transaction transaction = new Transaction(); try {/*from w w w. ja v a 2 s. c om*/ statement = connection.prepareStatement(CREATE_ACCOUNTOPERATIONS_STATEMENT); connection.setAutoCommit(false); statement.setInt(1, source_user_id); statement.setInt(2, ACCOUNT_OPERATION_PAYMENT); statement.setLong(3, amount); Date now = new Date(); java.sql.Timestamp sqlDate = new java.sql.Timestamp(now.getTime()); statement.setTimestamp(4, sqlDate); statement.setInt(5, source_user_id); statement.setInt(6, destination_user_id); statement.execute(); ResultSet rs = statement.getGeneratedKeys(); if (rs.next()) { transaction.setId(rs.getLong(1)); transaction.setAmount(amount); transaction.setDate(now); transaction.setSource_user_id(source_user_id); transaction.setDestination_user_id(destination_user_id); } statementAccountS = connection.prepareStatement(UPDATE_ACCOUNT_FOR_ADDITION_STATEMENT); statementAccountS.setLong(1, -amount); statementAccountS.setInt(2, source_user_id); statementAccountS.execute(); statementAccountD = connection.prepareStatement(UPDATE_ACCOUNT_FOR_ADDITION_STATEMENT); statementAccountD.setLong(1, amount); statementAccountD.setInt(2, destination_user_id); statementAccountD.execute(); connection.commit(); } catch (SQLException e) { if (connection != null) { connection.rollback(); } throw e; } finally { if (statement != null) { statement.close(); } if (statementAccountD != null) { statementAccountD.close(); } if (statementAccountS != null) { statementAccountS.close(); } if (connection != null) { connection.close(); } } return transaction; }
From source file:net.agmodel.metbroker.driver.impl.JmaGsmGl.java
/** * get database connection and execute SQL command. * And put the result to Sequence Object * @param seqMap Sequence Map//from w w w . j a va 2s . c o m * @param stationId station id * @param query SQL statement * @param start start date * @param end end date * @param hourly if true, use SIX_HOURS, else ONE_DAY * @throws DriverException something fail. */ private void queryTable(StationDataSetProxy seqMap, String stationId, String query, Date start, Date end, boolean hourly) throws DriverException { Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; java.sql.Timestamp startDate = new java.sql.Timestamp(start.getTime()); java.sql.Timestamp endDate = new java.sql.Timestamp(end.getTime()); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); try { con = dataSource.getConnection(); logger.debug("Connection: " + con.toString()); /* stmt = con.prepareStatement(query); stmt.setInt(1, new Integer(stationId).intValue()); stmt.setTimestamp(2, startDate, cal); stmt.setTimestamp(3, endDate, cal); stmt.setInt(4, new Integer(stationId).intValue()); stmt.setTimestamp(5, startDate, cal); stmt.setTimestamp(6, endDate, cal); */ stmt = con.prepareStatement(query); stmt.setInt(1, new Integer(stationId).intValue()); stmt.setTimestamp(2, startDate); stmt.setTimestamp(3, endDate); stmt.setInt(4, new Integer(stationId).intValue()); stmt.setTimestamp(5, startDate); stmt.setTimestamp(6, endDate); rs = stmt.executeQuery(); logger.debug("ResultSet: " + rs.toString()); AirTemperature tempSequence = null; if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) { tempSequence = (AirTemperature) seqMap.getSequence(MetElement.AIRTEMPERATURE); } Rain rainSequence = null; if (seqMap.containsKey(MetElement.RAIN)) { rainSequence = (Rain) seqMap.getSequence(MetElement.RAIN); } Humidity humiditySequence = null; if (seqMap.containsKey(MetElement.HUMIDITY)) { humiditySequence = (Humidity) seqMap.getSequence(MetElement.HUMIDITY); } Wind windSequence = null; if (seqMap.containsKey(MetElement.WIND)) { windSequence = (Wind) seqMap.getSequence(MetElement.WIND); } while (rs.next()) { java.util.Date recordTime = null; MutableInterval dataInterval = new MutableInterval(); recordTime = rs.getTimestamp("end_date"); if (hourly) { dataInterval.set(Duration.SIX_HOURS, recordTime); } else { dataInterval.set(Duration.ONE_DAY, recordTime); } if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) { float dummy = (float) (rs.getFloat("temperature") - 273.15); if (!rs.wasNull()) { ((AirTempMaxMinMeanImpl) tempSequence).putMeanOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.RAIN)) { float dummy = rs.getFloat("total_preciptasion"); if (!rs.wasNull()) { ((RainImpl) rainSequence).putRainfallOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.HUMIDITY)) { float dummy = rs.getFloat("relative_humidity"); if (!rs.wasNull()) { ((RHImpl) humiditySequence).putRHOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.WIND)) { float u = rs.getFloat("u_wind"); if (!rs.wasNull()) { float v = rs.getFloat("v_wind"); if (!rs.wasNull()) { ((Wind2DImpl) windSequence).putSpeedOverInterval(dataInterval, v, u); } } } } } catch (SQLException s) { s.printStackTrace(); } finally { try { rs.close(); } catch (Exception s) { } try { stmt.close(); } catch (Exception s) { } try { con.close(); } catch (Exception e) { } } }
From source file:com.adanac.module.blog.dao.AnswerDao.java
public Integer save(final Integer questionId, final String visitorIp, final Date answerDate, final String answer, final String username, final Integer referenceAnswerId) { return execute(new TransactionalOperation<Integer>() { @Override// www.j a va 2 s .co m public Integer doInConnection(Connection connection) { try { PreparedStatement statement = null; if (referenceAnswerId == null) { statement = connection.prepareStatement( "insert into answers (visitor_ip,city,answer,question_id," + "answer_date,username) values (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); } else { statement = connection.prepareStatement( "insert into answers (visitor_ip,city,answer,question_id," + "answer_date,username,reference_answer_id) values (?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); } statement.setString(1, visitorIp); statement.setString(2, Configuration.isProductEnv() ? HttpApiHelper.getCity(visitorIp) : "?"); statement.setString(3, answer); statement.setInt(4, questionId); Date finalCommentDate = answerDate; if (answerDate == null) { finalCommentDate = new Date(); } statement.setTimestamp(5, new Timestamp(finalCommentDate.getTime())); statement.setString(6, username); if (referenceAnswerId != null) { statement.setInt(7, referenceAnswerId); } int result = statement.executeUpdate(); if (result > 0) { ResultSet resultSet = statement.getGeneratedKeys(); if (resultSet.next()) { return resultSet.getInt(1); } } } catch (SQLException e) { error("save answers failed ...", e); } return null; } }); }