准备语句与Cassandra中的Bound语句?

时间:2014-08-05 02:16:58

标签: prepared-statement cassandra-2.0 datastax-java-driver

我想知道使用BoundStatement优于PreparedStatement的优势是什么?

PreparedStatement statement = session.prepare(
                      "INSERT INTO simplex.songs " +
                      "(id, title, album, artist) " +
                      "VALUES (?, ?, ?, ?);");

BoundStatement boundStatement = new BoundStatement(statement);
            session.execute(boundStatement.bind(
                  UUID.fromString("756716f7-2e54-4715-9f00-91debea6cf50"),
                  "La Petite Tonkinoise",
                  "Bye Bye Blackbird",
                  "Joséphine Baker");

最简单的方法是:

PreparedStatement ps = session.prepare(
                      "INSERT INTO simplex.songs " +
                      "(id, title, album, artist, tags) " +
                      "VALUES (?, ?, ?, ?, ?);");
ps.bind(UUID.fromString("756716f7-2e54-4715-9f00-91debea6cf50"),
                      "La Petite Tonkinoise",
                      "Bye Bye Blackbird",
                      "Joséphine Baker");

如您所见,我可以在没有preparedStatement的情况下将数据绑定到boundStatementsboundStatement在哪里有用?

2 个答案:

答案 0 :(得分:5)

没有优势:BoundStatement只不过是带有变量限制的PreparedStatement。事实上,PreparedStatements的bind()方法返回BoundStatement。

答案 1 :(得分:0)

对我来说,在PreparedStatement上调用bind(...)时会自动创建BoundStatement。您也可以直接创建实例BoundStatement。

PreparedStatement和BoundStatement具有不同的行为,因为PreparedStatement.bind()返回新实例BoundStatement,而BoundStatement.bind()返回自己。

这是多线程环境中的重要细节。 在共享的BoundStatement结果危险上调用方法.bind()

// shared instance BoundStatement on few threads 
BoundStatement bs1 = 
// bs2 is the same as bs1
// param1, param2, ... are different for every thread
BoundStatement bs2 = bs1.bind(param1, param2, ...);
// add some time to wait so other thread can modify your params
// Thread.sleep(RandomUtils.nextInt(100));        
// result2 sometimes may be with incorrect result 
results2 = session.execute(bs2); 

当您在PreparedStatement上调用bind时,您将获得不同的对象实例,并且它是线程安全的。 (与上述相同)

PreparedStatement ps1 = 
BoundStatement bs2 = ps1.bind(param1, param2, ...);
results2 = session.execute(bs2);