【问题标题】:Prepared statements vs Bound statements in Cassandra?Cassandra中准备好的语句与绑定语句?
【发布时间】:2014-09-27 14:36:51
【问题描述】:

我想知道使用BoundStatementPreparedStatement 相比有什么优势?

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在哪里有用?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      对我来说,BoundStatement 是在您对 PreparedStatement 调用 bind(...) 时自动创建的。也可以直接创建实例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); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-16
        • 1970-01-01
        • 2015-08-13
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 2015-08-01
        • 2018-10-11
        相关资源
        最近更新 更多