Java Code Examples for java.sql.PreparedStatement.setLong()

The following are Jave code examples for showing how to use setLong() of the java.sql.PreparedStatement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Reer   File: CrossVersionResultsStore.java   Source Code and License Vote up 7 votes
private void addOperations(PreparedStatement statement, long testId, String version, MeasuredOperationList operations) throws SQLException {
    for (MeasuredOperation operation : operations) {
        statement.setLong(1, testId);
        statement.setString(2, version);
        statement.setBigDecimal(3, operation.getTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(4, operation.getConfigurationTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(5, operation.getExecutionTime().toUnits(Duration.MILLI_SECONDS).getValue());
        statement.setBigDecimal(6, operation.getTotalMemoryUsed().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(7, operation.getTotalHeapUsage().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(8, operation.getMaxHeapUsage().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(9, operation.getMaxUncollectedHeap().toUnits(DataAmount.BYTES).getValue());
        statement.setBigDecimal(10, operation.getMaxCommittedHeap().toUnits(DataAmount.BYTES).getValue());
        if (operation.getCompileTotalTime() != null) {
            statement.setBigDecimal(11, operation.getCompileTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        } else {
            statement.setNull(11, Types.DECIMAL);
        }
        if (operation.getGcTotalTime() != null) {
            statement.setBigDecimal(12, operation.getGcTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
        } else {
            statement.setNull(12, Types.DECIMAL);
        }
        statement.addBatch();
    }
}
 
Example 2
Project: Rubicon   File: PermissionManager.java   Source Code and License Vote up 6 votes
/**
 * Adds a permission entry.
 * @param target the permission target.
 * @param permission the permission to add.
 * @return {@code false} if there already is an entry for {@code permission} and {@code target}.
 */
public boolean addPermission(PermissionTarget target, Permission permission) {
    if(hasPermission(target, permission, true))
        return false;
    try {
        PreparedStatement insertStatement = MySQL.getConnection()
                .prepareStatement("INSERT INTO `" + TABLE + "` " +
                        "(`guildid`, `type`, `id`, `permission`, `negated`) VALUES (?, ?, ?, ?, ?)");
        insertStatement.setLong(1, target.getGuild().getIdLong());
        insertStatement.setString(2, String.valueOf(target.getType().getIdentifier()));
        insertStatement.setLong(3, target.getId());
        insertStatement.setString(4, permission.getPermissionString());
        insertStatement.setBoolean(5, permission.isNegated());
        insertStatement.execute();
        return true;
    } catch (SQLException e) {
        throw new RuntimeException("An unknown error has occurred while saving data to the database.", e);
    }
}
 
Example 3
Project: otter-G   File: TestMysqlUnsignedNumber.java   Source Code and License Vote up 6 votes
public static void insertNumeric() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    Properties from = new Properties();
    from.put("user", "root");
    from.put("password", "root");
    from.put("characterEncoding", "utf8");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/erosa", from);
    PreparedStatement pst = conn.prepareStatement("insert into unsignednumeric(id,id1,id2,id3) values (?,?,?,?)");
    pst.setLong(1, Integer.MAX_VALUE * 2L);
    pst.setLong(2, Integer.MIN_VALUE);
    pst.setBigDecimal(3, new BigDecimal("18446744073709551614"));
    pst.setBigDecimal(4, new BigDecimal(Long.MIN_VALUE + ""));
    pst.executeUpdate();

    pst.close();
    conn.close();
}
 
Example 4
Project: ofmeet-openfire-plugin   File: Bookmark.java   Source Code and License Vote up 6 votes
/**
 * Saves a bookmark to the database.
 */
private void saveToDb() {
    Connection con = null;
    boolean abortTransaction = false;
    try {
        con = DbConnectionManager.getTransactionConnection();
        PreparedStatement pstmt = con.prepareStatement(SAVE_BOOKMARK);
        pstmt.setString(1, type.toString());
        pstmt.setString(2, name);
        pstmt.setString(3, value);
        pstmt.setInt(4, global ? 1 : 0);
        pstmt.setLong(5, bookmarkID);
        pstmt.executeUpdate();
        pstmt.close();
    }
    catch (SQLException sqle) {
        abortTransaction = true;
        Log.error(sqle.getMessage(), sqle);
    }
    finally {
        DbConnectionManager.closeTransactionConnection(con, abortTransaction);
    }
}
 
Example 5
Project: ofmeet-openfire-plugin   File: Bookmark.java   Source Code and License Vote up 6 votes
/**
 * Deletes a property from the db.
 */
private synchronized void deletePropertyFromDb(String name) {
    Connection con = null;
    PreparedStatement pstmt = null;
    boolean abortTransaction = false;
    try {
        con = DbConnectionManager.getTransactionConnection();
        pstmt = con.prepareStatement(DELETE_PROPERTY);
        pstmt.setLong(1, bookmarkID);
        pstmt.setString(2, name);
        pstmt.execute();
    }
    catch (SQLException sqle) {
        Log.error(sqle.getMessage(), sqle);
        abortTransaction = true;
    }
    finally {
        DbConnectionManager.closeTransactionConnection(pstmt, con, abortTransaction);
    }
}
 
Example 6
Project: Nird2   File: JdbcDatabase.java   Source Code and License Vote up 6 votes
@Override
public void incrementStreamCounter(Connection txn, ContactId c,
		TransportId t, long rotationPeriod) throws DbException {
	PreparedStatement ps = null;
	try {
		String sql = "UPDATE outgoingKeys SET stream = stream + 1"
				+ " WHERE contactId = ? AND transportId = ? AND period = ?";
		ps = txn.prepareStatement(sql);
		ps.setInt(1, c.getInt());
		ps.setString(2, t.getString());
		ps.setLong(3, rotationPeriod);
		int affected = ps.executeUpdate();
		if (affected != 1) throw new DbStateException();
		ps.close();
	} catch (SQLException e) {
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 7
Project: parabuild-ci   File: TestTimestamp.java   Source Code and License Vote up 6 votes
private void insertTestData() throws Exception {

//        conn.createStatement().executeUpdate("INSERT INTO \"SITE_LIST_SITE\" VALUES(23,1,'ru','RU',NULL,'\u041f\u0440\u043e\u0431\u043d\u044b\u0439 \u0441\u0430\u0439\u0442',NULL,0,'''/front_styles.css''',1,NULL,0)");
//        conn.createStatement().executeUpdate("INSERT INTO \"SITE_VIRTUAL_HOST\" VALUES(36,23,'test-host')");
//        conn.createStatement().executeUpdate("INSERT INTO \"SITE_SUPPORT_LANGUAGE\" VALUES(115,23,1,'ru_RU','ru_RU')");
//        conn.createStatement().executeUpdate("INSERT INTO \"CASH_CURRENCY\" VALUES(134,'\u0420\u0443\u0431',1,'\u0420\u0443\u0431',0,3,23,0.0)");
//        conn.createStatement().executeUpdate("INSERT INTO \"CASH_CURRENCY\" VALUES(135,'EURO',1,'EURO',0,7,23,0.0)");
        conn.createStatement().executeUpdate(
            "INSERT INTO \"CASH_CURRENCY\" VALUES(134,23)");
        conn.createStatement().executeUpdate(
            "INSERT INTO \"CASH_CURRENCY\" VALUES(135,23)");

        PreparedStatement ps = conn.prepareStatement("insert into "
            + nameTable + "(T, ID) values (?, ?)");

        ps.setTimestamp(1, testTS);
        ps.setLong(2, id);
        ps.executeUpdate();
        ps.close();

        ps = null;

        conn.commit();
    }
 
Example 8
Project: oscm   File: MigrationBillingResultAttributes.java   Source Code and License Vote up 6 votes
private void updateSubscriptionKey(long tkey, String subscriptionId,
        long organizationobjkey, long pmKey) throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("UPDATE billingresult SET subscriptionkey=");
    sb.append("(SELECT DISTINCT objkey FROM subscriptionhistory sh WHERE ");
    sb.append("sh.subscriptionid=? AND organizationobjkey=?");
    sb.append(" AND (select distinct pricemodelobjkey from producthistory prdh where prdh.objkey=sh.productobjkey and ?=prdh.pricemodelobjkey) is not null) ");
    sb.append("WHERE tkey=?");

    PreparedStatement pStatement = null;
    try {
        pStatement = getPreparedStatement(sb.toString());
        pStatement.setString(1, subscriptionId);
        pStatement.setLong(2, organizationobjkey);
        pStatement.setLong(3, pmKey);
        pStatement.setLong(4, tkey);
        pStatement.executeUpdate();
    } finally {
        closeStatement(pStatement, null);
    }
}
 
Example 9
Project: ofmeet-openfire-plugin   File: Bookmark.java   Source Code and License Vote up 6 votes
/**
 * Updates a property value in the database.
 */
private void updatePropertyInDb(String name, String value) {
    Connection con = null;
    PreparedStatement pstmt = null;
    boolean abortTransaction = false;
    try {
        con = DbConnectionManager.getTransactionConnection();
        pstmt = con.prepareStatement(UPDATE_PROPERTY);
        pstmt.setString(1, value);
        pstmt.setString(2, name);
        pstmt.setLong(3, bookmarkID);
        pstmt.executeUpdate();
    }
    catch (SQLException sqle) {
        Log.error(sqle.getMessage(), sqle);
        abortTransaction = true;
    }
    finally {
        DbConnectionManager.closeTransactionConnection(pstmt, con, abortTransaction);
    }
}
 
Example 10
Project: WurmMapGen   File: DatabaseConnection.java   Source Code and License Vote up 6 votes
/**
 * Creates a prepared statement with given properties
 * @param  sql   The SQL query
 * @param  args  The query values
 * @return  The prepared statement
 */
protected PreparedStatement prepareStatement(String sql, Object... args) throws SQLException {
	if (!isConnected()) return null;
	PreparedStatement statement = connection.prepareStatement(sql);
	
	if (args != null && args.length > 0) {
		for (int i = 0; i < args.length; i++) {
			if (args[i] instanceof String) statement.setString(i + 1, (String) args[i]);
			else if (args[i] instanceof Integer) statement.setInt(i + 1, (int) args[i]);
			else if (args[i] instanceof Long) statement.setLong(i + 1, (long) args[i]);
			else if (args[i] instanceof Boolean) statement.setBoolean(i + 1, (boolean) args[i]);
			else if (WurmMapGen.debug)
				throw new RuntimeException("Unknown type " + (args[i].getClass().getName()) + " in prepared statement");
		}
	}
	
	return statement;
}
 
Example 11
Project: message-broker   File: MessageDaoImpl.java   Source Code and License Vote up 5 votes
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
private void populateMessageWithMetadata(Connection connection,
                                         String idListAsString, List<Long> idList,
                                         Map<Long, Message> messageMap) throws SQLException, BrokerException {
    String metadataSql = "SELECT MESSAGE_ID, EXCHANGE_NAME, ROUTING_KEY, CONTENT_LENGTH, MESSAGE_METADATA "
            + " FROM MB_METADATA WHERE MESSAGE_ID IN (" + idListAsString + ") ORDER BY MESSAGE_ID";


    PreparedStatement selectMetadata = null;
    ResultSet metadataResultSet = null;

    try {
        selectMetadata = connection.prepareStatement(metadataSql);
        for (int i = 0; i < idList.size(); i++) {
            selectMetadata.setLong(i + 1, idList.get(i));
        }

        metadataResultSet = selectMetadata.executeQuery();
        while (metadataResultSet.next()) {
            long messageId = metadataResultSet.getLong(1);
            String exchangeName = metadataResultSet.getString(2);
            String routingKey = metadataResultSet.getString(3);
            long contentLength = metadataResultSet.getLong(4);
            byte[] bytes = metadataResultSet.getBytes(5);
            ByteBuf buffer = Unpooled.wrappedBuffer(bytes);
            try {
                Metadata metadata = new Metadata(messageId, routingKey, exchangeName, contentLength);
                metadata.setProperties(FieldTable.parse(buffer));
                metadata.setHeaders(FieldTable.parse(buffer));
                Message message = new Message(metadata);
                messageMap.put(messageId, message);
            } catch (Exception e) {
                throw new BrokerException("Error occurred while parsing metadata properties", e);
            } finally {
                buffer.release();
            }
        }
    } finally {
        close(metadataResultSet);
        close(selectMetadata);
    }
}
 
Example 12
Project: lams   File: ActivityDBLanguageUpdateTask.java   Source Code and License Vote up 5 votes
private void updateActivity(Connection conn) throws SQLException {
PreparedStatement stmt = null;
try {
    stmt = conn.prepareStatement(
	    "UPDATE lams_learning_activity SET language_file = ? WHERE learning_library_id  = ?");
    stmt.setString(1, languageFilename);
    stmt.setLong(2, activityId);
    stmt.execute();
} finally {
    DbUtils.closeQuietly(stmt);
}

   }
 
Example 13
Project: NapBot   File: NapBotDb.java   Source Code and License Vote up 5 votes
private static void setSchemaVersion(long version) throws SQLException
{
	PreparedStatement statement = prepare("UPDATE meta SET version = ?");
	try
	{
		statement.setLong(1, version);
		statement.executeUpdate();
	}
	finally
	{
		statement.close();
	}
}
 
Example 14
Project: parabuild-ci   File: TestSql.java   Source Code and License Vote up 5 votes
public void testAny() {

        try {
            String ddl =
                "drop table PRICE_RELATE_USER_ORDER_V2 if exists;"
                + "create table PRICE_RELATE_USER_ORDER_V2 "
                + "(ID_ORDER_V2 BIGINT, ID_USER NUMERIC, DATE_CREATE TIMESTAMP)";
            String sql = "insert into PRICE_RELATE_USER_ORDER_V2 "
                         + "(ID_ORDER_V2, ID_USER, DATE_CREATE) " + "values "
                         + "(?, ?, ?)";
            Statement st = connection.createStatement();

            st.execute(ddl);

            PreparedStatement ps = connection.prepareStatement(sql);

            ps.setLong(1, 1);
            ps.setNull(2, Types.NUMERIC);
            ps.setTimestamp(
                3, new java.sql.Timestamp(System.currentTimeMillis()));
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("TestSql.testAny() error: " + e.getMessage());
        }

        System.out.println("testAny complete");
    }
 
Example 15
Project: Nird2   File: JdbcDatabase.java   Source Code and License Vote up 5 votes
@Override
public void updateExpiryTime(Connection txn, ContactId c, MessageId m,
		int maxLatency) throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT txCount FROM statuses"
				+ " WHERE messageId = ? AND contactId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, m.getBytes());
		ps.setInt(2, c.getInt());
		rs = ps.executeQuery();
		if (!rs.next()) throw new DbStateException();
		int txCount = rs.getInt(1);
		if (rs.next()) throw new DbStateException();
		rs.close();
		ps.close();
		sql = "UPDATE statuses SET expiry = ?, txCount = txCount + 1"
				+ " WHERE messageId = ? AND contactId = ?";
		ps = txn.prepareStatement(sql);
		long now = clock.currentTimeMillis();
		ps.setLong(1, calculateExpiry(now, maxLatency, txCount));
		ps.setBytes(2, m.getBytes());
		ps.setInt(3, c.getInt());
		int affected = ps.executeUpdate();
		if (affected != 1) throw new DbStateException();
		ps.close();
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 16
Project: server   File: TransactionHelper.java   Source Code and License Vote up 5 votes
/**
 * Remove transaction from DB
 *
 * @param db data connection
 * @param id transaction id
 * @throws DataAccessException problems with the DB
 */
public static void remove(ConnectionProxy db, final long id) throws DataAccessException {

	try {

		PreparedStatement removeStatement = db.prepareStatement("delete from \"transaction\" where \"id\" = ?");
		synchronized (removeStatement) {

			removeStatement.setLong(1, id);
			removeStatement.executeUpdate();
		}

	} catch (Exception e) {

		throw new DataAccessException(e);
	}

}
 
Example 17
Project: oscm   File: DatabaseUpgradeTask.java   Source Code and License Vote up 5 votes
protected void updateBillingSharesResultTable(String tkey,
        String migratedXml) throws Exception {
    String sql = String.format("UPDATE %s SET %s=? WHERE tkey=?;",
            TABLE_BILLINGSHARESRESULT, COLUMN_RESULTXML);
    PreparedStatement stmt = getPreparedStatement(sql);
    stmt.setString(1, migratedXml);
    stmt.setLong(2, Long.parseLong(tkey));
    stmt.executeUpdate();
    stmt.close();
}
 
Example 18
Project: xitk   File: DataSourceWrapper.java   Source Code and License Vote up 5 votes
public boolean columnExists(Connection conn, String table, String column, Object value)
        throws DataAccessException {
    ParamUtil.requireNonBlank("table", table);
    ParamUtil.requireNonBlank("column", column);
    ParamUtil.requireNonNull("value", value);

    StringBuilder sb = new StringBuilder(2 * column.length() + 15);
    sb.append(column).append(" FROM ").append(table);
    sb.append(" WHERE ").append(column).append("=?");
    String sql = buildSelectFirstSql(1, sb.toString());

    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        stmt = (conn != null) ? conn.prepareStatement(sql)
                : getConnection().prepareStatement(sql);
        if (value instanceof Integer) {
            stmt.setInt(1, (Integer) value);
        } else if (value instanceof Long) {
            stmt.setLong(1, (Long) value);
        } else if (value instanceof String) {
            stmt.setString(1, (String) value);
        } else {
            stmt.setString(1, value.toString());
        }
        rs = stmt.executeQuery();
        return rs.next();
    } catch (SQLException ex) {
        throw translate(sql, ex);
    } finally {
        if (conn == null) {
            releaseResources(stmt, rs);
        } else {
            releaseStatementAndResultSet(stmt, rs);
        }
    }
}
 
Example 19
Project: oscm   File: DatabaseUpgradeTask.java   Source Code and License Vote up 5 votes
protected void updateBillingResultTable(String tkey, String migratedXml)
        throws Exception {
    String sql = String.format("UPDATE %s SET %s=? WHERE tkey=?;",
            TABLE_BILLINGRESULT, COLUMN_RESULTXML);
    PreparedStatement stmt = getPreparedStatement(sql);
    stmt.setString(1, migratedXml);
    stmt.setLong(2, Long.parseLong(tkey));
    stmt.executeUpdate();
    stmt.close();
}
 
Example 20
Project: iDataBaseConnection   File: SQLPreparedParamUtil.java   Source Code and License Vote up 4 votes
private static void setValue(PreparedStatement preStmt,int index,Value value)
{
	try 
	{
		if(value.isStringValue())
		{
			preStmt.setString(index, value.getString_value());
		}
		else if(value.isIntValue())
		{
			preStmt.setInt(index, value.getInt_value());
		}
		else if(value.isDoubleValue())
		{
			preStmt.setDouble(index, value.getDouble_value());
		}
		else if(value.isBooleanValue())
		{
			preStmt.setBoolean(index, value.getBoolean_value());
		}
		else if(value.isBlobValue())
		{
			preStmt.setBlob(index, value.getBlob_value());
		}
		else if(value.isBytesValue())
		{
			preStmt.setBytes(index, value.getBytes_value());
		}
		else if(value.isLongValue())
		{
			preStmt.setLong(index, value.getLong_value());
		}
		else if(value.isFloatValue())
		{
			preStmt.setFloat(index, value.getFloat_value());
		}
		else if(value.isBigdecimalValue())
		{
			preStmt.setBigDecimal(index, value.getBigdecimal_value());
		}
		else if(value.isByteValue())
		{
			preStmt.setByte(index, value.getByte_value());
		}
		else if(value.isDateValue())
		{
			preStmt.setDate(index, value.getDate_value());
		}
		else if(value.isTimeValue())
		{
			preStmt.setTime(index, value.getTime_value());
		}
		else
		{
			preStmt.setObject(index, value.getObject_value());
		}
		
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		DBCException.logException(DBCException.E_PreparedStatement, e);
	}
	
}