当前位置: 首页>>代码示例>>Java>>正文


Java PreparedStatement.bind方法代码示例

本文整理汇总了Java中com.datastax.driver.core.PreparedStatement.bind方法的典型用法代码示例。如果您正苦于以下问题:Java PreparedStatement.bind方法的具体用法?Java PreparedStatement.bind怎么用?Java PreparedStatement.bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.datastax.driver.core.PreparedStatement的用法示例。


在下文中一共展示了PreparedStatement.bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: bindKeyValue

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
/**
 * Binds Ignite cache key and value object to {@link PreparedStatement}.
 *
 * @param statement statement to which key and value object should be bind.
 * @param key key object.
 * @param val value object.
 * @return statement with bounded key and value.
 */
public BoundStatement bindKeyValue(PreparedStatement statement, Object key, Object val) {
    KeyPersistenceSettings keySettings = persistenceSettings.getKeyPersistenceSettings();
    Object[] keyValues = getBindingValues(keySettings.getStrategy(),
        keySettings.getSerializer(), keySettings.getFields(), key);
    ValuePersistenceSettings valSettings = persistenceSettings.getValuePersistenceSettings();
    Object[] valValues = getBindingValues(valSettings.getStrategy(),
        valSettings.getSerializer(), valSettings.getFields(), val);
    Object[] values = new Object[keyValues.length + valValues.length];
    int i = 0;
    for (Object keyVal : keyValues) {
        values[i] = keyVal;
        i++;
    }
    for (Object valVal : valValues) {
        values[i] = valVal;
        i++;
    }
    return statement.bind(values);
}
 
开发者ID:epam,项目名称:Lagerta,代码行数:28,代码来源:PersistenceController.java

示例2: main

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
public static void main(String[] args) {

		Session session = Connection.connect();		
		PreparedStatement preparedStatement = session.prepare("insert into user (id, name, age) values (?, ?, ?)");

		try {
			BoundStatement boundStatement = preparedStatement.bind(UUIDs.timeBased(), "Hector", 34);
			ResultSet rs = session.execute(boundStatement);
			System.out.println(rs);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		Connection.close();

	}
 
开发者ID:abulbasar,项目名称:cassandra-java-driver-examples,代码行数:17,代码来源:PreparedStatementExample.java

示例3: getFetchChunksAsyncFunction

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
private AsyncFunction<List<Long>, List<ResultSet>> getFetchChunksAsyncFunction(EntityId entityId, String key, Aggregation aggregation, long startTs, long endTs) {
    return partitions -> {
        try {
            PreparedStatement proto = getFetchStmt(aggregation);
            List<ResultSetFuture> futures = new ArrayList<>(partitions.size());
            for (Long partition : partitions) {
                log.trace("Fetching data for partition [{}] for entityType {} and entityId {}", partition, entityId.getEntityType(), entityId.getId());
                BoundStatement stmt = proto.bind();
                stmt.setString(0, entityId.getEntityType().name());
                stmt.setUUID(1, entityId.getId());
                stmt.setString(2, key);
                stmt.setLong(3, partition);
                stmt.setLong(4, startTs);
                stmt.setLong(5, endTs);
                log.debug("Generated query [{}] for entityType {} and entityId {}", stmt, entityId.getEntityType(), entityId.getId());
                futures.add(executeAsyncRead(stmt));
            }
            return Futures.allAsList(futures);
        } catch (Throwable e) {
            log.error("Failed to fetch data", e);
            throw e;
        }
    };
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:25,代码来源:CassandraBaseTimeseriesDao.java

示例4: cleanDirtyRow

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
/**
 * Remove the entries from the dirty row (for this replica) that correspond to a set of primary keys
 * @param tableName the table we are removing dirty entries from
 * @param keys the primary key values to use in the DELETE.  Note: this is *only* the primary keys, not a full table row.
 */
@Override
public void cleanDirtyRow(String tableName, Object[] keys) {
	TableInfo ti = dbi.getTableInfo(tableName);
	StringBuilder cols = new StringBuilder("REPLICA__=?");
	List<Object> vallist = new ArrayList<Object>();
	vallist.add(myId);
	int n = 0;
	for (int i = 0; i < ti.columns.size(); i++) {
		if (ti.iskey.get(i)) {
			cols.append(" AND ").append(ti.columns.get(i)).append("=?");
			vallist.add(keys[n++]);
		}
	}
	String cql = String.format("DELETE FROM %s.DIRTY_%s WHERE %s;", music_ns, tableName, cols.toString());
	logger.debug("Executing MUSIC write:"+ cql);
	Session sess = getMusicSession();
	PreparedStatement ps = getPreparedStatementFromCache(cql);
	BoundStatement bound = ps.bind(vallist.toArray());
	bound.setReadTimeoutMillis(60000);
	synchronized (sess) {
		sess.execute(bound);
	}
}
 
开发者ID:att,项目名称:music,代码行数:29,代码来源:CassandraMixin.java

示例5: markDirtyRow

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
/**
 * Mark rows as "dirty" in the dirty rows table for <i>tableName</i>.  Rows are marked for all replicas but
 * this one (this replica already has the up to date data).
 * @param tableName the table we are marking dirty
 * @param keys an ordered list of the values being put into the table.  The values that correspond to the tables'
 * primary key are copied into the dirty row table.
 */
@Override
public void markDirtyRow(String tableName, Object[] keys) {
	String cql = String.format("INSERT INTO %s.%s (tablename, replica, keyset) VALUES (?, ?, ?);", music_ns, DIRTY_TABLE);
	Session sess = getMusicSession();
	PreparedStatement ps = getPreparedStatementFromCache(cql);
	Object[] values = new Object[] { tableName, "", buildJSON(tableName, keys) };
	for (String repl : allReplicaIds) {
		if (!repl.equals(myId)) {
			values[1] = repl;
			logger.debug("Executing MUSIC write:"+ cql + " with values " + values[0] + " " + values[1] + " " + values[2]);
			BoundStatement bound = ps.bind(values);
			bound.setReadTimeoutMillis(60000);
			synchronized (sess) {
				sess.execute(bound);
			}
		}
	}
}
 
开发者ID:att,项目名称:music,代码行数:26,代码来源:Cassandra2Mixin.java

示例6: readSharedQueryTextsUsingPS

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
private List<Trace.SharedQueryText> readSharedQueryTextsUsingPS(String agentId, String traceId,
        PreparedStatement readPS) throws Exception {
    BoundStatement boundStatement = readPS.bind();
    boundStatement.setString(0, agentId);
    boundStatement.setString(1, traceId);
    ResultSet results = session.execute(boundStatement);
    List<Trace.SharedQueryText> sharedQueryTexts = Lists.newArrayList();
    while (!results.isExhausted()) {
        Row row = results.one();
        int i = 0;
        String truncatedText = checkNotNull(row.getString(i++));
        String truncatedEndText = row.getString(i++);
        String fullTextSha1 = row.getString(i++);
        Trace.SharedQueryText.Builder sharedQueryText = Trace.SharedQueryText.newBuilder();
        if (fullTextSha1 == null) {
            sharedQueryText.setFullText(truncatedText);
        } else {
            sharedQueryText.setFullTextSha1(fullTextSha1)
                    .setTruncatedText(truncatedText)
                    .setTruncatedEndText(checkNotNull(truncatedEndText));
        }
        sharedQueryTexts.add(sharedQueryText.build());
    }
    return sharedQueryTexts;
}
 
开发者ID:glowroot,项目名称:glowroot,代码行数:26,代码来源:TraceDaoImpl.java

示例7: getNeedsRollupFromChildrenList

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
static List<NeedsRollupFromChildren> getNeedsRollupFromChildrenList(String agentRollupId,
        PreparedStatement readNeedsRollupFromChild, Session session) throws Exception {
    BoundStatement boundStatement = readNeedsRollupFromChild.bind();
    boundStatement.setString(0, agentRollupId);
    ResultSet results = session.execute(boundStatement);
    Map<Long, NeedsRollupFromChildren> needsRollupFromChildrenMap = Maps.newLinkedHashMap();
    for (Row row : results) {
        int i = 0;
        long captureTime = checkNotNull(row.getTimestamp(i++)).getTime();
        UUID uniqueness = row.getUUID(i++);
        String childAgentRollupId = checkNotNull(row.getString(i++));
        Set<String> keys = checkNotNull(row.getSet(i++, String.class));
        NeedsRollupFromChildren needsRollup = needsRollupFromChildrenMap.get(captureTime);
        if (needsRollup == null) {
            needsRollup = new NeedsRollupFromChildren(captureTime);
            needsRollupFromChildrenMap.put(captureTime, needsRollup);
        }
        for (String key : keys) {
            needsRollup.keys.put(key, childAgentRollupId);
        }
        needsRollup.uniquenessKeysForDeletion.add(uniqueness);
    }
    return ImmutableList.copyOf(needsRollupFromChildrenMap.values());
}
 
开发者ID:glowroot,项目名称:glowroot,代码行数:25,代码来源:Common.java

示例8: populateV09AgentRollupTable

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
private void populateV09AgentRollupTable() throws Exception {
    Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
    PreparedStatement insertPS = null;
    for (V09AgentRollup v09AgentRollup : v09AgentRollups.values()) {
        if (v09AgentRollup.agent() && v09AgentRollup.hasRollup()) {
            // only create v09_agent_check and v09_last_capture_time tables if needed
            if (insertPS == null) {
                dropTableIfExists("v09_agent_rollup");
                session.createTableWithLCS("create table v09_agent_rollup (one int,"
                        + " v09_agent_id varchar, v09_agent_rollup_id varchar, primary key"
                        + " (one, v09_agent_id, v09_agent_rollup_id))");
                insertPS = session.prepare("insert into v09_agent_rollup"
                        + " (one, v09_agent_id, v09_agent_rollup_id) values (1, ?, ?)");
            }
            BoundStatement boundStatement = insertPS.bind();
            boundStatement.setString(0, v09AgentRollup.agentRollupId());
            int i = 0;
            boundStatement.setString(i++, v09AgentRollup.v09AgentRollupId());
            boundStatement.setString(i++,
                    checkNotNull(v09AgentRollup.v09ParentAgentRollupId()));
            session.execute(boundStatement);
        }
    }
}
 
开发者ID:glowroot,项目名称:glowroot,代码行数:25,代码来源:SchemaUpgrade.java

示例9: addDefaultGaugeNameToUiConfigs

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
private void addDefaultGaugeNameToUiConfigs() throws Exception {
    PreparedStatement insertPS = session.prepare("insert into agent_config (agent_rollup_id,"
            + " config, config_update, config_update_token) values (?, ?, ?, ?)");
    ResultSet results = session.execute("select agent_rollup_id, config from agent_config");
    for (Row row : results) {
        String agentRollupId = row.getString(0);
        AgentConfig oldAgentConfig;
        try {
            oldAgentConfig = AgentConfig.parseFrom(checkNotNull(row.getBytes(1)));
        } catch (InvalidProtocolBufferException e) {
            logger.error(e.getMessage(), e);
            continue;
        }
        AgentConfig agentConfig = oldAgentConfig.toBuilder()
                .setUiConfig(oldAgentConfig.getUiConfig().toBuilder()
                        .addAllDefaultGaugeName(ConfigDefaults.UI_DEFAULT_GAUGE_NAMES))
                .build();
        BoundStatement boundStatement = insertPS.bind();
        int i = 0;
        boundStatement.setString(i++, agentRollupId);
        boundStatement.setBytes(i++, ByteBuffer.wrap(agentConfig.toByteArray()));
        boundStatement.setBool(i++, true);
        boundStatement.setUUID(i++, UUIDs.random());
        session.execute(boundStatement);
    }
}
 
开发者ID:glowroot,项目名称:glowroot,代码行数:27,代码来源:SchemaUpgrade.java

示例10: rewriteTraceAttributeNameTablePart1

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
private void rewriteTraceAttributeNameTablePart1() throws Exception {
    dropTableIfExists("trace_attribute_name_temp");
    session.execute("create table trace_attribute_name_temp (agent_rollup varchar,"
            + " transaction_type varchar, trace_attribute_name varchar, primary key"
            + " ((agent_rollup, transaction_type), trace_attribute_name))");
    PreparedStatement insertTempPS = session.prepare("insert into trace_attribute_name_temp"
            + " (agent_rollup, transaction_type, trace_attribute_name) values (?, ?, ?)");
    ResultSet results = session.execute("select agent_rollup, transaction_type,"
            + " trace_attribute_name from trace_attribute_name");
    for (Row row : results) {
        BoundStatement boundStatement = insertTempPS.bind();
        boundStatement.setString(0, row.getString(0));
        boundStatement.setString(1, row.getString(1));
        boundStatement.setString(2, row.getString(2));
        session.execute(boundStatement);
    }
}
 
开发者ID:glowroot,项目名称:glowroot,代码行数:18,代码来源:SchemaUpgrade.java

示例11: rewriteOpenIncidentTablePart1

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
private void rewriteOpenIncidentTablePart1() throws Exception {
    dropTableIfExists("open_incident_temp");
    session.execute("create table open_incident_temp (one int, agent_rollup_id varchar,"
            + " condition blob, severity varchar, notification blob, open_time timestamp,"
            + " primary key (one, agent_rollup_id, condition, severity))");
    PreparedStatement insertTempPS = session.prepare("insert into open_incident_temp (one,"
            + " agent_rollup_id, condition, severity, notification, open_time) values"
            + " (1, ?, ?, ?, ?, ?)");
    ResultSet results = session.execute("select agent_rollup_id, condition, severity,"
            + " notification, open_time from open_incident where one = 1");
    for (Row row : results) {
        BoundStatement boundStatement = insertTempPS.bind();
        boundStatement.setString(0, row.getString(0));
        boundStatement.setBytes(1, row.getBytes(1));
        boundStatement.setString(2, row.getString(2));
        boundStatement.setBytes(3, row.getBytes(3));
        boundStatement.setTimestamp(4, row.getTimestamp(4));
        session.execute(boundStatement);
    }
}
 
开发者ID:glowroot,项目名称:glowroot,代码行数:21,代码来源:SchemaUpgrade.java

示例12: insertMulti

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
@Override
	public Status insertMulti(List<TsPoint> points) {
		long costTime = 0L;
		if (points != null) {
			Cluster cluster = null;
			try {
//				cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
//				Session session = cluster.connect(KEY_SPACE_NAME);
				Session session = SessionManager.getSession();
				BatchStatement batch = new BatchStatement();
				PreparedStatement ps = session.prepare(
						"INSERT INTO " + TABLE_NAME + "(timestamp,device_code,sensor_code,value) VALUES(?,?,?,?)");
				for (TsPoint point : points) {
					BoundStatement bs = ps.bind(new Date(point.getTimestamp()), point.getDeviceCode(),
							point.getSensorCode(), Double.parseDouble(point.getValue().toString()));
					batch.add(bs);
				}
				long startTime = System.nanoTime();
				session.execute(batch);
				long endTime = System.nanoTime();
				costTime = endTime - startTime;
				batch.clear();
//				session.close();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (cluster != null)
					cluster.close();
			}
		}
//		System.out.println("costTime=" + costTime);
		return Status.OK(costTime);
	}
 
开发者ID:dbiir,项目名称:ts-benchmark,代码行数:34,代码来源:CassandraDB.java

示例13: updatePoints

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
@Override
	public Status updatePoints(List<TsPoint> points) {
		long costTime = 0L;
		if (points != null) {
			Cluster cluster = null;
			try {
//				cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
//				Session session = cluster.connect(KEY_SPACE_NAME);
				Session session = SessionManager.getSession();
				BatchStatement batch = new BatchStatement();
				PreparedStatement ps = session.prepare(
						"UPDATE " + TABLE_NAME + " SET value=? WHERE timestamp=? and device_code=? and sensor_code=?");
				for (TsPoint point : points) {
					BoundStatement bs = ps.bind(Double.parseDouble(point.getValue().toString()),new Date(point.getTimestamp()), point.getDeviceCode(),
							point.getSensorCode());
					batch.add(bs);
				}
				long startTime = System.nanoTime();
				session.execute(batch);
				long endTime = System.nanoTime();
				costTime = endTime - startTime;
				batch.clear();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (cluster != null)
					cluster.close();
			}
		}
//		System.out.println("此次更新消耗时间[" + costTime / 1000 + "]s");
		return Status.OK(costTime);
	}
 
开发者ID:dbiir,项目名称:ts-benchmark,代码行数:33,代码来源:CassandraDB.java

示例14: findAllAsyncSequentiallyWithLimit

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
private void findAllAsyncSequentiallyWithLimit(final TsKvQueryCursor cursor, final SimpleListenableFuture<List<TsKvEntry>> resultFuture) {
    if (cursor.isFull() || !cursor.hasNextPartition()) {
        resultFuture.set(cursor.getData());
    } else {
        PreparedStatement proto = getFetchStmt(Aggregation.NONE);
        BoundStatement stmt = proto.bind();
        stmt.setString(0, cursor.getEntityType());
        stmt.setUUID(1, cursor.getEntityId());
        stmt.setString(2, cursor.getKey());
        stmt.setLong(3, cursor.getNextPartition());
        stmt.setLong(4, cursor.getStartTs());
        stmt.setLong(5, cursor.getEndTs());
        stmt.setInt(6, cursor.getCurrentLimit());

        Futures.addCallback(executeAsyncRead(stmt), new FutureCallback<ResultSet>() {
            @Override
            public void onSuccess(@Nullable ResultSet result) {
                cursor.addData(convertResultToTsKvEntryList(result.all()));
                findAllAsyncSequentiallyWithLimit(cursor, resultFuture);
            }

            @Override
            public void onFailure(Throwable t) {
                log.error("[{}][{}] Failed to fetch data for query {}-{}", stmt, t);
            }
        }, readResultsProcessingExecutor);
    }
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:29,代码来源:CassandraBaseTimeseriesDao.java

示例15: markDirtyRow

import com.datastax.driver.core.PreparedStatement; //导入方法依赖的package包/类
/**
 * Mark rows as "dirty" in the dirty rows table for <i>tableName</i>.  Rows are marked for all replicas but
 * this one (this replica already has the up to date data).
 * @param tableName the table we are marking dirty
 * @param keys an ordered list of the values being put into the table.  The values that correspond to the tables'
 * primary key are copied into the dirty row table.
 */
@Override
public void markDirtyRow(String tableName, Object[] keys) {
	TableInfo ti = dbi.getTableInfo(tableName);
	StringBuilder cols = new StringBuilder("REPLICA__");
	StringBuilder vals = new StringBuilder("?");
	List<Object> vallist = new ArrayList<Object>();
	vallist.add(""); // placeholder for replica
	for (int i = 0; i < ti.columns.size(); i++) {
		if (ti.iskey.get(i)) {
			cols.append(", ").append(ti.columns.get(i));
			vals.append(", ").append("?");
			vallist.add(keys[i]);
		}
	}
	String cql = String.format("INSERT INTO %s.DIRTY_%s (%s) VALUES (%s);", music_ns, tableName, cols.toString(), vals.toString());
	Session sess = getMusicSession();
	PreparedStatement ps = getPreparedStatementFromCache(cql);
	for (String repl : allReplicaIds) {
		if (!repl.equals(myId)) {
			logger.debug("Executing MUSIC write:"+ cql);
			vallist.set(0, repl);
			BoundStatement bound = ps.bind(vallist.toArray());
			bound.setReadTimeoutMillis(60000);
			synchronized (sess) {
				sess.execute(bound);
			}
		}
	}
}
 
开发者ID:att,项目名称:music,代码行数:37,代码来源:CassandraMixin.java


注:本文中的com.datastax.driver.core.PreparedStatement.bind方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。