我正在使用Datastax驱动程序将数据读写到Cassandra中。我使用的是datastax驱动程序3.1.0,而cassandra集群版本为2.0.10。
我在下面创建了两个方法来执行cql查询。
当我不需要在cql查询中设置任何值时,我将调用第一个方法,因此它适用于cql字符串,如下所示:
select * from testkeyspace.testtable where row_id=1 // cql-1
select * from testkeyspace.meta where row_id=1 // cql-2
select * from testkeyspace.proc where row_id=1 // cql-3现在,每当有这样的查询时,我需要调用第二个方法:
select * from testkeyspace.testtabletwo where row_id=1 and active=? // cql-4
select * from testkeyspace.storage where topic=? and parts=? // cql-5, in this part is Integer and topic is String.因此,我的问题是如何使第二个方法更通用,以便如果我需要使用BoundStatement在cql查询中设置n个值,那么它应该能工作吗?现在,我不确定在调用第二个传递给该方法的值的方法时,应该对cql-4和cql-5做什么?我知道我必须使用BoundStatement设置这些值,但是如果我需要设置两个或三个或四个值,我如何才能使该方法成为通用方法,这样就不需要对任何东西进行硬编码?有些可以是整数,有些可以是字符串。
第一方法:-
public ResultSet executeQuery(final String cql) {
return executeWithSession(new SessionCallable<ResultSet>() {
@Override
public ResultSet executeWithSession(Session session) {
BoundStatement bs = getStatement(cql);
bs.setConsistencyLevel(consistencyLevel);
return session.execute(bs);
}
});
}第二种方法:-
public ResultSet executeQuery(final String cql, final Object... values) {
return executeWithSession(new SessionCallable<ResultSet>() {
@Override
public ResultSet executeWithSession(Session session) {
BoundStatement bs = getStatement(cql);
bs.setConsistencyLevel(consistencyLevel);
// how to set these **values** into my cql query using BoundStatement in a generic way
// so that I don't need to hardcode anything for cql-4 and cql-5
return session.execute(cql, values);
}
});
}
// cache the prepared statement
private BoundStatement getStatement(final String cql) {
Session session = getSession();
PreparedStatement ps = cache.get(cql);
// no statement cached, create one and cache it now.
if (ps == null) {
ps = session.prepare(cql);
PreparedStatement old = cache.putIfAbsent(cql, ps);
if (old != null)
ps = old;
}
return ps.bind();
}我必须在这里使用BoundStatement吗?我想我必须这么做,因为这就是我能设定一致性水平的方法?
发布于 2017-01-20 11:29:54
怎么说呢:
public ResultSet executeQuery(final String cql, final Object... values) {
return executeWithSession(new SessionCallable<ResultSet>() {
@Override
public ResultSet executeWithSession(Session session) {
BoundStatement bs = getStatement(cql, values);
bs.setConsistencyLevel(consistencyLevel);
return session.execute(cql);
}
});
}
// cache the prepared statement
private BoundStatement getStatement(final String cql, Object... values) {
Session session = getSession();
PreparedStatement ps = cache.get(cql);
// no statement cached, create one and cache it now.
if (ps == null) {
ps = session.prepare(cql);
PreparedStatement old = cache.putIfAbsent(cql, ps);
if (old != null)
ps = old;
}
return ps.bind(values);
}https://stackoverflow.com/questions/41757029
复制相似问题