Cassandra中的准备语句与绑定语句?

pkmbmrz7  于 2022-09-27  发布在  Cassandra
关注(0)|答案(2)|浏览(165)

我想知道使用BoundStatement相对于e1d1e有什么优势?

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的情况下将数据绑定到preparedStatementboundStatement在哪里有用?

pjngdqdw

pjngdqdw1#

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

xqk2d5yq

xqk2d5yq2#

对于我来说,在PreparedStatement上调用bind(…)时,会自动创建BoundStatement。也可以直接创建示例BoundStatement。
PreparedStatement和BoundStatement具有不同的行为,因为Prepared语句。bind()返回新示例BoundStatement,而BoundStatement。bind()返回自己。
这是多线程环境中的重要细节。对共享的BoundStatement结果危险调用method.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);

相关问题