title: How to use prepared statement efficiently using datastax java driver in Cassandra?
body: <p>I need to query one of the tables in Cassandra using Datastax Java driver. Below is the code I have which works fine -</p>
  
  <pre><code>public class TestCassandra {
  
          private Session session = null;
          private Cluster cluster = null;
  
          private static class ConnectionHolder {
              static final TestCassandra connection = new TestCassandra();
          }
  
          public static TestCassandra getInstance() {
              return ConnectionHolder.connection;
          }
  
          private TestCassandra() {
              Builder builder = Cluster.builder();
              builder.addContactPoints("127.0.0.1");
  
              PoolingOptions opts = new PoolingOptions();
              opts.setCoreConnectionsPerHost(HostDistance.LOCAL, opts.getCoreConnectionsPerHost(HostDistance.LOCAL));
  
              cluster = builder.withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE).withPoolingOptions(opts)
                      .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("DC2")))
                      .withReconnectionPolicy(new ConstantReconnectionPolicy(100L))
                      .build();
              session = cluster.connect();
          }
  
      private Set&lt;String&gt; getRandomUsers() {
          Set&lt;String&gt; userList = new HashSet&lt;String&gt;();
  
          for (int table = 0; table &lt; 14; table++) {
              String sql = "select * from testkeyspace.test_table_" + table + ";";
  
              try {
                  SimpleStatement query = new SimpleStatement(sql);
                  query.setConsistencyLevel(ConsistencyLevel.QUORUM);
                  ResultSet res = session.execute(query);
  
                  Iterator&lt;Row&gt; rows = res.iterator();
                  while (rows.hasNext()) {
                      Row r = rows.next();
  
                      String user_id = r.getString("user_id");
                      userList.add(user_id);
                  }
              } catch (Exception e) {
                  System.out.println("error= " + ExceptionUtils.getStackTrace(e));
              }
          }
  
          return userList;
      }
  }
  </code></pre>
  
  <p>I am using above class like this in my main application - </p>
  
  <pre><code>TestCassandra.getInstance().getRandomUsers();
  </code></pre>
  
  <p>Is there any way I can use <code>PreparedStatement</code> in <code>getRandomUsers</code> efficiently? I guess I need to make sure that I am creating <code>PreparedStatement</code> only once instead of creating it multiple times. What is the best design for that in my current architecture and how can I use it?</p>