本文整理汇总了Java中com.datastax.driver.core.Statement类的典型用法代码示例。如果您正苦于以下问题:Java Statement类的具体用法?Java Statement怎么用?Java Statement使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Statement类属于com.datastax.driver.core包,在下文中一共展示了Statement类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: executeAdaptiveQueryAsync
import com.datastax.driver.core.Statement; //导入依赖的package包/类
private static ListenableFuture<ResultSet> executeAdaptiveQueryAsync(Session session, Statement statement, int fetchSize,
int remainingAdaptations) {
statement.setFetchSize(fetchSize);
ResultSetFuture rawFuture = session.executeAsync(statement);
// Lazily wrap the result set from the async result with an AdaptiveResultSet
ListenableFuture<ResultSet> adaptiveFuture = Futures.transform(rawFuture, new Function<ResultSet, ResultSet>() {
@Override
public ResultSet apply(ResultSet resultSet) {
return new AdaptiveResultSet(session, resultSet, remainingAdaptations);
}
});
return Futures.withFallback(adaptiveFuture, t -> {
if (isAdaptiveException(t) && remainingAdaptations > 0 && fetchSize > MIN_FETCH_SIZE) {
// Try again with half the fetch size
int reducedFetchSize = Math.max(fetchSize / 2, MIN_FETCH_SIZE);
_log.debug("Repeating previous query with fetch size {} due to {}", reducedFetchSize, t.getMessage());
return executeAdaptiveQueryAsync(session, statement, reducedFetchSize, remainingAdaptations - 1);
}
throw Throwables.propagate(t);
});
}
示例2: queryForLastWriteTimes
import com.datastax.driver.core.Statement; //导入依赖的package包/类
@Override
public DBResult queryForLastWriteTimes()
{
if (cluster == null)
return null;
try (Session session = cluster.newSession())
{
Statement statement = new SimpleStatement(String.format("SELECT WRITETIME (%s) FROM %s.%s;", columnName, keyspace, tableName));
statement.setConsistencyLevel(ConsistencyLevel.ALL);
ResultSet results = session.execute(statement);
List<Row> allRows = results.all();
// sort all of the rows accordingly
allRows.sort(new RowComparator());
// gather the information we need
long startTime = allRows.get(0).getLong(0) / 1000;
long endTime = allRows.get(allRows.size() - 1).getLong(0) / 1000;
int totalCount = allRows.size();
return new DBResult(startTime, endTime, totalCount);
}
}
示例3: untilApplied
import com.datastax.driver.core.Statement; //导入依赖的package包/类
public static boolean untilApplied(Session session, BatchStatement.Type type, Consumer<BatchStatement> transaction) {
for (int i = 1; i <= MAX_RETRY; i ++) {
BatchStatement batchStatement = new BatchStatement(type);
transaction.accept(batchStatement);
if (batchStatement.size() == 0) return false;
boolean applied;
if (batchStatement.size() > 1) {
applied = session.execute(batchStatement).wasApplied();
} else {
Statement statement = Iterables.getOnlyElement(batchStatement.getStatements());
applied = session.execute(statement).wasApplied();
}
if (applied) return true;
log.warn("Attempt {}/{} failed executing {}", i, MAX_RETRY, batchStatement);
try {
Thread.sleep(100 * i);
} catch (InterruptedException e) {
throw new AttemptsFailedException(e);
}
}
throw new AttemptsFailedException();
}
示例4: uploadPackage
import com.datastax.driver.core.Statement; //导入依赖的package包/类
@Override
public long uploadPackage(DataPackage dataPack) {
long time = System.currentTimeMillis();
try {
Session session;
Cluster cluster;
cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
session = cluster.connect();
ByteBuffer buffer = ByteBuffer.wrap(dataPack.getData());
Statement statement = QueryBuilder.insertInto(DATABASE, MAIN_TABLE)
.value(COL_ID, time)
.value(COL_DATA, buffer)
.value(COL_DESC, dataPack.getDescription());
session.execute(statement);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return time;
}
示例5: downloadPackage
import com.datastax.driver.core.Statement; //导入依赖的package包/类
@Override
public DataPackage downloadPackage(long packageID) {
DataPackage dataPack = new DataPackage();
try {
Session session;
Cluster cluster;
cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
session = cluster.connect();
Statement statement = QueryBuilder.select()
.all()
.from(DATABASE, MAIN_TABLE)
.where(eq(COL_ID, packageID));
ResultSet results = session.execute(statement);
for(Row row : results) {
dataPack.setId(row.getLong(COL_ID));
dataPack.setDescription(row.getString(COL_DESC));
dataPack.setData(row.getBytes(COL_DATA).array());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return dataPack;
}
示例6: listPackages
import com.datastax.driver.core.Statement; //导入依赖的package包/类
@Override
public List<DataPackage> listPackages() {
List<DataPackage> dataPacks = new ArrayList<>();
try {
Session session;
Cluster cluster;
cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
session = cluster.connect();
Statement statement = QueryBuilder.select()
.all()
.from(DATABASE, MAIN_TABLE);
ResultSet results = session.execute(statement);
for(Row row : results) {
DataPackage dataPack = new DataPackage();
dataPack.setId(row.getLong(COL_ID));
dataPack.setDescription(row.getString(COL_DESC));
dataPacks.add(dataPack);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return dataPacks;
}
示例7: tuneStatementExecutionOptions
import com.datastax.driver.core.Statement; //导入依赖的package包/类
/**
* Tunes CQL statement execution options (consistency level, fetch option and etc.).
*
* @param statement Statement.
* @return Modified statement.
*/
private Statement tuneStatementExecutionOptions(Statement statement) {
String qry = "";
if (statement instanceof BoundStatement) {
qry = ((BoundStatement)statement).preparedStatement().getQueryString().trim().toLowerCase();
}
else if (statement instanceof PreparedStatement) {
qry = ((PreparedStatement)statement).getQueryString().trim().toLowerCase();
}
boolean readStatement = qry.startsWith("select");
boolean writeStatement = statement instanceof Batch || statement instanceof BatchStatement ||
qry.startsWith("insert") || qry.startsWith("delete") || qry.startsWith("update");
if (readStatement && readConsistency != null) {
statement.setConsistencyLevel(readConsistency);
}
if (writeStatement && writeConsistency != null) {
statement.setConsistencyLevel(writeConsistency);
}
if (fetchSize != null) {
statement.setFetchSize(fetchSize);
}
return statement;
}
示例8: findListByStatementAsync
import com.datastax.driver.core.Statement; //导入依赖的package包/类
protected ListenableFuture<List<D>> findListByStatementAsync(Statement statement) {
if (statement != null) {
statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
ResultSetFuture resultSetFuture = getSession().executeAsync(statement);
return Futures.transform(resultSetFuture, new Function<ResultSet, List<D>>() {
@Nullable
@Override
public List<D> apply(@Nullable ResultSet resultSet) {
Result<E> result = getMapper().map(resultSet);
if (result != null) {
List<E> entities = result.all();
return DaoUtil.convertDataList(entities);
} else {
return Collections.emptyList();
}
}
});
}
return Futures.immediateFuture(Collections.emptyList());
}
示例9: findOneByStatementAsync
import com.datastax.driver.core.Statement; //导入依赖的package包/类
protected ListenableFuture<D> findOneByStatementAsync(Statement statement) {
if (statement != null) {
statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
ResultSetFuture resultSetFuture = getSession().executeAsync(statement);
return Futures.transform(resultSetFuture, new Function<ResultSet, D>() {
@Nullable
@Override
public D apply(@Nullable ResultSet resultSet) {
Result<E> result = getMapper().map(resultSet);
if (result != null) {
E entity = result.one();
return DaoUtil.getData(entity);
} else {
return null;
}
}
});
}
return Futures.immediateFuture(null);
}
示例10: update
import com.datastax.driver.core.Statement; //导入依赖的package包/类
@Override public void update(Host host, Statement statement, Exception e, long nanos) {
if (!(statement instanceof NamedBoundStatement)) return;
Span span = cache.remove(statement);
if (span == null) {
if (statement.isTracing()) {
LOG.warn("{} not in the cache eventhough tracing is on", statement);
}
return;
}
span.setDuration(nanos / 1000); // TODO: allow client tracer to end with duration
Endpoint local = span.getAnnotations().get(0).host; // TODO: expose in brave
long endTs = span.getTimestamp() + span.getDuration();
if (e != null) {
span.addToBinary_annotations(BinaryAnnotation.create("cql.error", e.getMessage(), local));
} else {
span.addToAnnotations(Annotation.create(endTs, "cr", local));
}
int ipv4 = ByteBuffer.wrap(host.getAddress().getAddress()).getInt();
Endpoint endpoint = Endpoint.create("cassandra", ipv4, host.getSocketAddress().getPort());
span.addToBinary_annotations(BinaryAnnotation.address("sa", endpoint));
collector.collect(span);
}
示例11: update
import com.datastax.driver.core.Statement; //导入依赖的package包/类
@Override public void update(Host host, Statement statement, Exception e, long nanos) {
if (!(statement instanceof BoundStatement)) return;
Span span = cache.remove(statement);
if (span == null) {
if (statement.isTracing()) {
LOG.warn("{} not in the cache eventhough tracing is on", statement);
}
return;
}
span.setDuration(nanos / 1000); // TODO: allow client tracer to end with duration
Endpoint local = span.getAnnotations().get(0).host; // TODO: expose in brave
long endTs = span.getTimestamp() + span.getDuration();
span.addToAnnotations(Annotation.create(endTs, "cr", local));
if (e != null) {
span.addToBinary_annotations(BinaryAnnotation.create(Constants.ERROR, e.getMessage(), local));
}
int ipv4 = ByteBuffer.wrap(host.getAddress().getAddress()).getInt();
Endpoint endpoint = Endpoint.create("cassandra3", ipv4, host.getSocketAddress().getPort());
span.addToBinary_annotations(BinaryAnnotation.address("sa", endpoint));
collector.collect(span);
}
示例12: executePut
import com.datastax.driver.core.Statement; //导入依赖的package包/类
public void executePut(String query, String consistency){
logger.debug("in data store handle, executing put:"+query);
long start = System.currentTimeMillis();
Statement statement = new SimpleStatement(query);
if(consistency.equalsIgnoreCase("critical")){
logger.info("Executing critical put query:"+query);
statement.setConsistencyLevel(ConsistencyLevel.QUORUM);
}
else if (consistency.equalsIgnoreCase("eventual")){
logger.info("Executing normal put query:"+query);
statement.setConsistencyLevel(ConsistencyLevel.ONE);
}
session.execute(statement);
long end = System.currentTimeMillis();
logger.debug("Time taken for actual put in cassandra:"+(end-start));
}
示例13: getStatementArguments
import com.datastax.driver.core.Statement; //导入依赖的package包/类
/**
* Get the arguments of a statement in an ordered key-value array.
*
* @param arg0
* The statement.
* @return The key-value array.
*/
public static String[] getStatementArguments( Statement arg0 ) {
String[] returnValue = EMTPY_STRING_ARRAY;
if ( arg0 instanceof ProfiledBoundStatement ) {
returnValue = ( (ProfiledBoundStatement) arg0 ).getArgumentList();
} else if ( arg0 instanceof BatchStatement ) {
List<String> argumentList = new ArrayList<String>();
Collection<Statement> statements = ( (BatchStatement) arg0 ).getStatements();
for ( Statement statement : statements ) {
String[] statementArguments = getStatementArguments( statement );
Collections.addAll( argumentList, statementArguments );
}
returnValue = argumentList.toArray( new String[argumentList.size()] );
}
return returnValue;
}
示例14: getStatementName
import com.datastax.driver.core.Statement; //导入依赖的package包/类
/**
* Get the name of a statement.
*
* @param arg0 The statement.
* @return The name used for logging.
*/
public static String getStatementName( Statement arg0 ) {
String returnValue = "unknown";
if ( arg0 instanceof RegularStatement ) {
returnValue = ( (RegularStatement) arg0 ).getQueryString();
} else if ( arg0 instanceof BoundStatement ) {
PreparedStatement preparedStatement = ( (BoundStatement) arg0 ).preparedStatement();
returnValue = preparedStatement.getQueryString();
} else if ( arg0 instanceof BatchStatement ) {
StringBuilder value = new StringBuilder( "Batch : " );
Collection<Statement> statements = ( (BatchStatement) arg0 ).getStatements();
boolean first = true;
for ( Statement statement : statements ) {
if ( first ) {
first = false;
} else {
value.append( ", " );
}
String statementName = getStatementName( statement );
value.append( statementName );
}
returnValue = value.toString();
}
return returnValue;
}
示例15: prepareStatement
import com.datastax.driver.core.Statement; //导入依赖的package包/类
private Statement prepareStatement(final String query) {
Statement stmt = null;
if (query.length() <= POOLABLE_LENGTH) {
PoolableWrapper<Statement> wrapper = stmtPool.get(query);
if (wrapper != null) {
stmt = wrapper.value();
}
}
if (stmt == null) {
final NamedCQL namedCQL = getNamedCQL(query);
final String cql = namedCQL.getPureCQL();
stmt = bind(prepare(cql));
if (query.length() <= POOLABLE_LENGTH) {
stmtPool.put(query, PoolableWrapper.of(stmt));
}
}
return stmt;
}