List of usage examples for java.sql PreparedStatement setDouble
void setDouble(int parameterIndex, double x) throws SQLException;
double
value. From source file:com.opensymphony.module.propertyset.database.JDBCPropertySet.java
private void setValues(PreparedStatement ps, int type, String key, Object value) throws SQLException, PropertyException { // Patched by Edson Richter for MS SQL Server JDBC Support! String driverName;/*from w w w . j ava 2s. c o m*/ try { driverName = ps.getConnection().getMetaData().getDriverName().toUpperCase(); } catch (Exception e) { driverName = ""; } ps.setNull(1, Types.VARCHAR); ps.setNull(2, Types.TIMESTAMP); // Patched by Edson Richter for MS SQL Server JDBC Support! // Oracle support suggestion also Michael G. Slack if ((driverName.indexOf("SQLSERVER") >= 0) || (driverName.indexOf("ORACLE") >= 0)) { ps.setNull(3, Types.BINARY); } else { ps.setNull(3, Types.BLOB); } ps.setNull(4, Types.FLOAT); ps.setNull(5, Types.NUMERIC); ps.setInt(6, type); ps.setString(7, globalKey); ps.setString(8, key); switch (type) { case PropertySet.BOOLEAN: Boolean boolVal = (Boolean) value; ps.setInt(5, boolVal.booleanValue() ? 1 : 0); break; case PropertySet.DATA: Data data = (Data) value; ps.setBytes(3, data.getBytes()); break; case PropertySet.DATE: Date date = (Date) value; ps.setTimestamp(2, new Timestamp(date.getTime())); break; case PropertySet.DOUBLE: Double d = (Double) value; ps.setDouble(4, d.doubleValue()); break; case PropertySet.INT: Integer i = (Integer) value; ps.setInt(5, i.intValue()); break; case PropertySet.LONG: Long l = (Long) value; ps.setLong(5, l.longValue()); break; case PropertySet.STRING: ps.setString(1, (String) value); break; default: throw new PropertyException("This type isn't supported!"); } }
From source file:com.l2jfree.gameserver.model.sevensigns.SevenSigns.java
/** * Saves all Seven Signs data, both to the database and properties file (if updateSettings = True). Often called to preserve data integrity and * synchronization with DB, in case of errors. <BR> * If player != null, just that player's data is updated in the database, otherwise all player's data is sequentially updated. * // w w w . j a v a2 s. c o m * @param player * @param updateSettings * @throws Exception */ public void saveSevenSignsData(L2Player player, boolean updateSettings) { Connection con = null; if (_log.isDebugEnabled()) _log.info("SevenSigns: Saving data to disk."); try { con = L2DatabaseFactory.getInstance().getConnection(con); for (StatsSet sevenDat : _signsPlayerData.values()) { if (player != null) if (sevenDat.getInteger("charId") != player.getObjectId()) continue; PreparedStatement statement = con.prepareStatement( "UPDATE seven_signs SET cabal=?, seal=?, red_stones=?, " + "green_stones=?, blue_stones=?, " + "ancient_adena_amount=?, contribution_score=? " + "WHERE charId=?"); statement.setString(1, sevenDat.getString("cabal")); statement.setInt(2, sevenDat.getInteger("seal")); statement.setInt(3, sevenDat.getInteger("red_stones")); statement.setInt(4, sevenDat.getInteger("green_stones")); statement.setInt(5, sevenDat.getInteger("blue_stones")); statement.setDouble(6, sevenDat.getDouble("ancient_adena_amount")); statement.setDouble(7, sevenDat.getDouble("contribution_score")); statement.setInt(8, sevenDat.getInteger("charId")); statement.execute(); statement.close(); if (_log.isDebugEnabled()) _log.info("SevenSigns: Updated data in database for char ID " + sevenDat.getInteger("charId") + " (" + sevenDat.getString("cabal") + ")"); } if (updateSettings) { String sqlQuery = "UPDATE seven_signs_status SET current_cycle=?, active_period=?, previous_winner=?, " + "dawn_stone_score=?, dawn_festival_score=?, dusk_stone_score=?, dusk_festival_score=?, " + "avarice_owner=?, gnosis_owner=?, strife_owner=?, avarice_dawn_score=?, gnosis_dawn_score=?, " + "strife_dawn_score=?, avarice_dusk_score=?, gnosis_dusk_score=?, strife_dusk_score=?, " + "festival_cycle=?, "; for (int i = 0; i < (SevenSignsFestival.FESTIVAL_COUNT); i++) sqlQuery += "accumulated_bonus" + String.valueOf(i) + "=?, "; sqlQuery += "date=? WHERE id=0"; PreparedStatement statement = con.prepareStatement(sqlQuery); statement.setInt(1, _currentCycle); statement.setInt(2, _activePeriod); statement.setInt(3, _previousWinner); statement.setDouble(4, _dawnStoneScore); statement.setInt(5, _dawnFestivalScore); statement.setDouble(6, _duskStoneScore); statement.setInt(7, _duskFestivalScore); statement.setInt(8, _signsSealOwners.get(SEAL_AVARICE)); statement.setInt(9, _signsSealOwners.get(SEAL_GNOSIS)); statement.setInt(10, _signsSealOwners.get(SEAL_STRIFE)); statement.setInt(11, _signsDawnSealTotals.get(SEAL_AVARICE)); statement.setInt(12, _signsDawnSealTotals.get(SEAL_GNOSIS)); statement.setInt(13, _signsDawnSealTotals.get(SEAL_STRIFE)); statement.setInt(14, _signsDuskSealTotals.get(SEAL_AVARICE)); statement.setInt(15, _signsDuskSealTotals.get(SEAL_GNOSIS)); statement.setInt(16, _signsDuskSealTotals.get(SEAL_STRIFE)); statement.setInt(17, SevenSignsFestival.getInstance().getCurrentFestivalCycle()); for (int i = 0; i < SevenSignsFestival.FESTIVAL_COUNT; i++) statement.setInt(18 + i, SevenSignsFestival.getInstance().getAccumulatedBonus(i)); statement.setInt(18 + SevenSignsFestival.FESTIVAL_COUNT, Calendar.getInstance().get(Calendar.DAY_OF_WEEK)); statement.execute(); statement.close(); if (_log.isDebugEnabled()) _log.info("SevenSigns: Updated data in database."); } } catch (SQLException e) { _log.fatal("SevenSigns: Unable to save data to database: ", e); } finally { L2DatabaseFactory.close(con); } }
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); }// w w w . j a va 2 s. c om 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:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.PhoenixHBaseAccessor.java
public void insertMetricRecords(TimelineMetrics metrics) throws SQLException, IOException { List<TimelineMetric> timelineMetrics = metrics.getMetrics(); if (timelineMetrics == null || timelineMetrics.isEmpty()) { LOG.debug("Empty metrics insert request."); return;/* ww w.ja va 2s . co m*/ } Connection conn = getConnection(); PreparedStatement metricRecordStmt = null; long currentTime = System.currentTimeMillis(); try { metricRecordStmt = conn.prepareStatement(String.format(UPSERT_METRICS_SQL, METRICS_RECORD_TABLE_NAME)); for (TimelineMetric metric : timelineMetrics) { metricRecordStmt.clearParameters(); if (LOG.isTraceEnabled()) { LOG.trace("host: " + metric.getHostName() + ", " + "metricName = " + metric.getMetricName() + ", " + "values: " + metric.getMetricValues()); } double[] aggregates = AggregatorUtils.calculateAggregates(metric.getMetricValues()); metricRecordStmt.setString(1, metric.getMetricName()); metricRecordStmt.setString(2, metric.getHostName()); metricRecordStmt.setString(3, metric.getAppId()); metricRecordStmt.setString(4, metric.getInstanceId()); metricRecordStmt.setLong(5, currentTime); metricRecordStmt.setLong(6, metric.getStartTime()); metricRecordStmt.setString(7, metric.getType()); metricRecordStmt.setDouble(8, aggregates[0]); metricRecordStmt.setDouble(9, aggregates[1]); metricRecordStmt.setDouble(10, aggregates[2]); metricRecordStmt.setLong(11, (long) aggregates[3]); String json = TimelineUtils.dumpTimelineRecordtoJSON(metric.getMetricValues()); metricRecordStmt.setString(12, json); try { metricRecordStmt.executeUpdate(); } catch (SQLException sql) { LOG.error(sql); } } conn.commit(); } finally { if (metricRecordStmt != null) { try { metricRecordStmt.close(); } catch (SQLException e) { // Ignore } } if (conn != null) { try { conn.close(); } catch (SQLException sql) { // Ignore } } } }
From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.test.AbstractDataEnabledJdbcCrawlerTestCase.java
/** * {@inheritDoc} Called by the JUnit-Runner before execution of a testMethod of inheriting classes. Sets up a Database * fixture by performing the following steps: * <ol>//from www . java 2s .c o m * <li>Shutdown a (potentially) running Derby engine by calling {@link DriverManager#getConnection(String)} with the * Shutdown-URL (see {@link #SHUTDOWN_URL}).</li> * <li>Delete all database files (potentially) remaining from prior test cases.</li> * <li>Configure Derby engine to log all executed SQL in the log file and to rather append to an existing logfile than * to overwrite it.</li> * <li>Get a {@link Connection} to the Derby DB and insert 100 rows of data (see source code for details). This * includes BLOB (from image file) and CLOB (from text file) fields.</li> * <li>Release allocated JDBC-resources (Statement, Connection).</li> * <li>Shutdown Derby Engine via Shutdown-URL (so the Crawler can start it up as it would normally)</li> * <li>Instantiates a {@link JdbcCrawler}.</li> * </ol> * * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); Class.forName(DRIVER_NAME).newInstance(); // shutdown embedded Derby engine (if running) // using SHUTDOWN_URL *always* results in SQLException, so we catch and ignore ... try { DriverManager.getConnection(SHUTDOWN_URL); } catch (final SQLException e) { _log.info("Testcase Setup: Shutting down Derby Engine"); } // delete existing db files final File dbDirectory = new File(DB_NAME); if (FileUtils.deleteQuietly(dbDirectory)) { _log.info("Deleted DB files of [" + DB_NAME + "] database"); } else { _log.warn("Could not delete DB files of [" + DB_NAME + "] database"); } Class.forName(DRIVER_NAME).newInstance(); final Properties p = System.getProperties(); // we want to see all sql in the db log file p.put("derby.language.logStatementText", "true"); // we don't want the logfile to be recreated each time the engine starts ... p.put("derby.infolog.append", "true"); Connection connection = DriverManager.getConnection(CONNECTION_URL); final ArrayList<Statement> statements = new ArrayList<Statement>(); // list of Statements, // PreparedStatements PreparedStatement psInsert = null; Statement createStatement = null; createStatement = connection.createStatement(); statements.add(createStatement); // create a person table... createStatement .execute("CREATE TABLE person(id int, vorname varchar(40), name varchar(40), strasse varchar(40), " + "plz varchar(5), ort varchar(40), festnetz varchar(20), body_mass_index double, vacationdays " + "integer, birthday date, scheduled_for_downsizing smallint, downsized timestamp, photo blob, cv clob)"); _log.info("Created TABLE [person]"); // insert 100 records ... psInsert = connection .prepareStatement("INSERT INTO person VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"); statements.add(psInsert); // prepare resource files for blob / clob insertion... final File resDir = new File(RES_FOLDER_PATH); final File photoFile = new File(resDir, PHOTO_FILE_NAME); final File cvFile = new File(resDir, CV_FILE_NAME); for (int i = 1; i <= RECORDS_TO_INSERT; i++) { psInsert.setInt(COLUMN_ID, i); psInsert.setString(COLUMN_FIRSTNAME, "Mustervorname" + i); psInsert.setString(COLUMN_SURNAME, "Mustername" + i); psInsert.setString(COLUMN_STREET, "Musterstrasse " + i); psInsert.setString(COLUMN_PLZ, String.valueOf(getRandomInteger(DIGITS_IN_PLZ))); psInsert.setString(COLUMN_CITY, "Musterstadt" + i); psInsert.setString(COLUMN_PHONE, "0" + getRandomInteger(DIGITS_IN_AREA_CODE) + "-" + getRandomInteger(DIGITS_IN_EXTENSION)); psInsert.setDouble(COLUMN_BMI, (Math.random() / Math.random())); psInsert.setLong(COLUMN_VACATIONDAYS, getRandomInteger(MAX_VACATIONDAYS)); psInsert.setDate(COLUMN_BIRTHDAY, new Date(new java.util.Date().getTime())); psInsert.setBoolean(COLUMN_SCHEDULED_FOR_DOWNSIZING, ((getRandomInteger(1) % 2) == 0)); psInsert.setDate(COLUMN_DOWNSIZED, new Date(new java.util.Date().getTime())); psInsert.setBytes(COLUMN_PHOTO, FileUtils.readFileToByteArray(photoFile)); psInsert.setString(COLUMN_CV, FileUtils.readFileToString(cvFile)); psInsert.execute(); } // release all open resources to avoid unnecessary memory usage for (final Statement st : statements) { try { st.close(); } catch (final SQLException sqle) { _log.error("Could not release Statement", sqle); } } statements.clear(); // Connection try { if (connection != null) { connection.close(); connection = null; } } catch (final SQLException sqle) { _log.error("Could not release Connection", sqle); } // shutdown Derby engine AGAIN, so the Crawler can start it up as it would normally try { DriverManager.getConnection(SHUTDOWN_URL); } catch (final SQLException e) { _log.info("Testcase Setup: Shutting down Derby Engine"); } _crawler = new JdbcCrawler(); }
From source file:org.waarp.common.database.data.AbstractDbData.java
/** * Set Value into PreparedStatement/*from ww w.ja va 2 s . c o 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.apache.phoenix.query.BaseTest.java
protected static void initATableValues(String tenantId, byte[][] splits, Date date, Long ts, String url) throws Exception { if (ts == null) { ensureTableCreated(url, ATABLE_NAME, splits); } else {/* w w w . jav a 2 s . c o m*/ ensureTableCreated(url, ATABLE_NAME, splits, ts - 5); } Properties props = new Properties(); if (ts != null) { props.setProperty(CURRENT_SCN_ATTRIB, Long.toString(ts - 3)); } Connection conn = DriverManager.getConnection(url, props); try { // Insert all rows at ts PreparedStatement stmt = conn.prepareStatement("upsert into " + "ATABLE(" + " ORGANIZATION_ID, " + " ENTITY_ID, " + " A_STRING, " + " B_STRING, " + " A_INTEGER, " + " A_DATE, " + " X_DECIMAL, " + " X_LONG, " + " X_INTEGER," + " Y_INTEGER," + " A_BYTE," + " A_SHORT," + " A_FLOAT," + " A_DOUBLE," + " A_UNSIGNED_FLOAT," + " A_UNSIGNED_DOUBLE)" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, tenantId); stmt.setString(2, ROW1); stmt.setString(3, A_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 1); stmt.setDate(6, date); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 1); stmt.setShort(12, (short) 128); stmt.setFloat(13, 0.01f); stmt.setDouble(14, 0.0001); stmt.setFloat(15, 0.01f); stmt.setDouble(16, 0.0001); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW2); stmt.setString(3, A_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 2); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 2); stmt.setShort(12, (short) 129); stmt.setFloat(13, 0.02f); stmt.setDouble(14, 0.0002); stmt.setFloat(15, 0.02f); stmt.setDouble(16, 0.0002); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW3); stmt.setString(3, A_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 3); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 3); stmt.setShort(12, (short) 130); stmt.setFloat(13, 0.03f); stmt.setDouble(14, 0.0003); stmt.setFloat(15, 0.03f); stmt.setDouble(16, 0.0003); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW4); stmt.setString(3, A_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 4); stmt.setDate(6, date == null ? null : date); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 4); stmt.setShort(12, (short) 131); stmt.setFloat(13, 0.04f); stmt.setDouble(14, 0.0004); stmt.setFloat(15, 0.04f); stmt.setDouble(16, 0.0004); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW5); stmt.setString(3, B_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 5); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 5); stmt.setShort(12, (short) 132); stmt.setFloat(13, 0.05f); stmt.setDouble(14, 0.0005); stmt.setFloat(15, 0.05f); stmt.setDouble(16, 0.0005); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW6); stmt.setString(3, B_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 6); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 6); stmt.setShort(12, (short) 133); stmt.setFloat(13, 0.06f); stmt.setDouble(14, 0.0006); stmt.setFloat(15, 0.06f); stmt.setDouble(16, 0.0006); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW7); stmt.setString(3, B_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 7); stmt.setDate(6, date == null ? null : date); stmt.setBigDecimal(7, BigDecimal.valueOf(0.1)); stmt.setLong(8, 5L); stmt.setInt(9, 5); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 7); stmt.setShort(12, (short) 134); stmt.setFloat(13, 0.07f); stmt.setDouble(14, 0.0007); stmt.setFloat(15, 0.07f); stmt.setDouble(16, 0.0007); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW8); stmt.setString(3, B_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 8); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, BigDecimal.valueOf(3.9)); long l = Integer.MIN_VALUE - 1L; assert (l < Integer.MIN_VALUE); stmt.setLong(8, l); stmt.setInt(9, 4); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 8); stmt.setShort(12, (short) 135); stmt.setFloat(13, 0.08f); stmt.setDouble(14, 0.0008); stmt.setFloat(15, 0.08f); stmt.setDouble(16, 0.0008); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW9); stmt.setString(3, C_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 9); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, BigDecimal.valueOf(3.3)); l = Integer.MAX_VALUE + 1L; assert (l > Integer.MAX_VALUE); stmt.setLong(8, l); stmt.setInt(9, 3); stmt.setInt(10, 300); stmt.setByte(11, (byte) 9); stmt.setShort(12, (short) 0); stmt.setFloat(13, 0.09f); stmt.setDouble(14, 0.0009); stmt.setFloat(15, 0.09f); stmt.setDouble(16, 0.0009); stmt.execute(); conn.commit(); } finally { conn.close(); } }
From source file:org.opennms.upgrade.implementations.MonitoringLocationsMigratorOffline.java
@Override public void execute() throws OnmsUpgradeException { if (monitoringLocationsConfig == null) return;//from ww w. ja v a2 s. c o m log("Moving monitoring locations into the database...\n"); long count = 0; try { Connection connection = null; final DBUtils dbUtils = new DBUtils(getClass()); try { connection = DataSourceFactory.getInstance().getConnection(); dbUtils.watch(connection); PreparedStatement insertLocation = connection.prepareStatement( "INSERT INTO monitoringlocations (id, monitoringarea, geolocation, latitude, longitude, priority) VALUES (?,?,?,?,?,?)"); PreparedStatement insertPollingPackage = connection.prepareStatement( "INSERT INTO monitoringlocationspollingpackages (monitoringlocationid, packagename) VALUES (?,?)"); PreparedStatement insertCollectionPackage = connection.prepareStatement( "INSERT INTO monitoringlocationscollectionpackages (monitoringlocationid, packagename) VALUES (?,?)"); PreparedStatement insertTag = connection.prepareStatement( "INSERT INTO monitoringlocationstags (monitoringlocationid, tag) VALUES (?,?)"); dbUtils.watch(insertLocation); dbUtils.watch(insertPollingPackage); dbUtils.watch(insertCollectionPackage); dbUtils.watch(insertTag); for (LocationDef location : monitoringLocationsConfig.getLocations()) { insertLocation.setString(1, location.getLocationName()); // id insertLocation.setString(2, location.getMonitoringArea()); // monitoringarea if (location.getGeolocation() != null && !"".equals(location.getGeolocation().trim())) { insertLocation.setString(3, location.getGeolocation()); // geolocation } else { insertLocation.setNull(3, Types.VARCHAR); } if (location.getCoordinates() != null && !"".equals(location.getCoordinates())) { String[] latLong = location.getCoordinates().split(","); if (latLong.length == 2) { insertLocation.setDouble(4, Double.valueOf(latLong[0])); // latitude insertLocation.setDouble(5, Double.valueOf(latLong[1])); // longitude } else { insertLocation.setNull(4, Types.DOUBLE); insertLocation.setNull(5, Types.DOUBLE); } } else { insertLocation.setNull(4, Types.DOUBLE); insertLocation.setNull(5, Types.DOUBLE); } if (location.getPriority() == null) { insertLocation.setNull(6, Types.INTEGER); // priority } else { insertLocation.setLong(6, location.getPriority()); // priority } insertLocation.execute(); count++; if (location.getPollingPackageName() != null && !"".equals(location.getPollingPackageName())) { insertPollingPackage.setString(1, location.getLocationName()); // monitoringlocationid insertPollingPackage.setString(2, location.getPollingPackageName()); // packagename insertPollingPackage.execute(); } if (location.getCollectionPackageName() != null && !"".equals(location.getCollectionPackageName())) { insertCollectionPackage.setString(1, location.getLocationName()); // monitoringlocationid insertCollectionPackage.setString(2, location.getCollectionPackageName()); // packagename insertCollectionPackage.execute(); } for (Tag tag : location.getTags()) { if (tag.getName() != null && !"".equals(tag.getName().trim())) { insertTag.setString(1, location.getLocationName()); // monitoringlocationid insertTag.setString(2, tag.getName()); // tag insertTag.execute(); } } } } finally { dbUtils.cleanUp(); } } catch (Throwable e) { throw new OnmsUpgradeException("Can't fix services configuration because " + e.getMessage(), e); } log("Moved %d monitoring locations into the database\n", count); }
From source file:com.draagon.meta.manager.db.ObjectManagerDB.java
protected PreparedStatement getPreparedStatement(Connection c, String query, Collection<?> args) throws MetaException, SQLException { String sql = query; // (String) mOQLCache.get( query ); // If it's not in the cache, then parse it and put it there //if ( sql == null ) //{//from ww w . j ava2 s.co m //Map<String,MetaClass> m = getMetaClassMap( query ); //if ( m.size() > 0 ) { // sql = convertToSQL( query, m ); //} //else sql = query; //mOQLCache.put( query, sql ); //} PreparedStatement s = c.prepareStatement(sql); if (args != null) { int i = 1; for (Object o : args) { if (o instanceof Boolean) { s.setBoolean(i, (Boolean) o); } else if (o instanceof Byte) { s.setByte(i, (Byte) o); } else if (o instanceof Short) { s.setShort(i, (Short) o); } else if (o instanceof Integer) { s.setInt(i, (Integer) o); } else if (o instanceof Long) { s.setLong(i, (Long) o); } else if (o instanceof Float) { s.setFloat(i, (Float) o); } else if (o instanceof Double) { s.setDouble(i, (Double) o); } else if (o instanceof Date) { s.setTimestamp(i, new Timestamp(((Date) o).getTime())); } else if (o == null) { s.setString(i, null); } else { s.setString(i, o.toString()); } // Increment the i i++; } } return s; }
From source file:org.nuxeo.ecm.core.storage.sql.db.dialect.DialectPostgreSQL.java
@Override public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column) throws SQLException { switch (column.getJdbcType()) { case Types.VARCHAR: case Types.CLOB: String v;/* ww w . j a v a 2 s. co m*/ if (column.getType() == ColumnType.BLOBID) { v = ((Binary) value).getDigest(); } else { v = (String) value; } ps.setString(index, v); break; case Types.BIT: ps.setBoolean(index, ((Boolean) value).booleanValue()); return; case Types.SMALLINT: ps.setInt(index, ((Long) value).intValue()); return; case Types.INTEGER: case Types.BIGINT: ps.setLong(index, ((Long) value).longValue()); return; case Types.DOUBLE: ps.setDouble(index, ((Double) value).doubleValue()); return; case Types.TIMESTAMP: Calendar cal = (Calendar) value; Timestamp ts = new Timestamp(cal.getTimeInMillis()); ps.setTimestamp(index, ts, cal); // cal passed for timezone return; case Types.ARRAY: Array array = createArrayOf(Types.VARCHAR, (Object[]) value, ps.getConnection()); ps.setArray(index, array); return; case Types.OTHER: if (column.getType() == ColumnType.FTSTORED) { ps.setString(index, (String) value); return; } throw new SQLException("Unhandled type: " + column.getType()); default: throw new SQLException("Unhandled JDBC type: " + column.getJdbcType()); } }