Cassandra中的预处理语句与绑定语句有何区别?

9

我想知道使用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");

正如您所看到的,我可以在不使用boundStatements的情况下将数据绑定到preparedStatement中。那么boundStatement在哪些情况下会发挥重要作用呢?

2个回答

9

没有优势:BoundStatement 仅仅是一个绑定了变量的 PreparedStatement。实际上,PreparedStatement 的 bind() 方法返回的就是 BoundStatement。


1

当您在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); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接