Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepared statements vs Bound statements in Cassandra?

I am wondering what is the advantage of using BoundStatement over 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");

The simplest way would be:

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");

As you can see, I can bind data to preparedStatement without boundStatements. Where are boundStatement useful?

like image 487
brain storm Avatar asked Aug 05 '14 02:08

brain storm


2 Answers

No advantage: a BoundStatement is nothing more than a PreparedStatement with variables bounded. The bind() method of a PreparedStatements, in fact, returns a BoundStatement.

like image 134
Carlo Bertuccini Avatar answered Sep 28 '22 09:09

Carlo Bertuccini


For me BoundStatement is created automatically when you invoke bind(...) on PreparedStatement. Also you can create instance BoundStatement directly.

PreparedStatement and BoundStatement has different behavior because PreparedStatement.bind() return new instance BoundStatement, while BoundStatement.bind() return himself.

It is important detail in multithreaded enviroment. Invoking method .bind() on shared BoundStatement result hazard

// 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); 

When you invoke bind on PreparedStatement you will get different instance of object and it is thread safe. (In the same scenario as above)

PreparedStatement ps1 = 
BoundStatement bs2 = ps1.bind(param1, param2, ...);
results2 = session.execute(bs2); 
like image 42
Krzysztof Czerw Avatar answered Sep 28 '22 09:09

Krzysztof Czerw