Scylla Documentation Logo Documentation
  • Server
    • Scylla Open Source
    • Scylla Enterprise
    • Scylla Alternator
  • Cloud
    • Scylla Cloud
    • Scylla Cloud Docs
  • Tools
    • Scylla Manager
    • Scylla Monitoring Stack
    • Scylla Operator
  • Drivers
    • CQL Drivers
    • DynamoDB Drivers
Download
Menu

Caution

You're viewing documentation for a previous version of Scylla Java Driver. Switch to the latest stable version.

Scylla Java Driver Manual Core driver Statements Simple statements

Simple statements¶

Quick overview¶

For one-off executions of a raw query string.

  • create with SimpleStatement.newInstance() or SimpleStatement.builder().

  • values: ? or :name, fill with setPositionalValues() or setNamedValues() respectively. Driver has to guess target CQL types, this can lead to ambiguities.

  • built-in implementation is immutable. Setters always return a new object, don’t ignore the result.


Use SimpleStatement for queries that will be executed only once (or just a few times):

SimpleStatement statement =
    SimpleStatement.newInstance(
        "SELECT value FROM application_params WHERE name = 'greeting_message'");
session.execute(statement);

Each time you execute a simple statement, Cassandra parses the query string again; nothing is cached (neither on the client nor on the server):

client                             driver                Cassandra
--+----------------------------------+---------------------+------
  |                                  |                     |
  | session.execute(SimpleStatement) |                     |
  |--------------------------------->|                     |
  |                                  | QUERY(query_string) |
  |                                  |-------------------->|
  |                                  |                     |
  |                                  |                     |
  |                                  |                     | - parse query string
  |                                  |                     | - execute query
  |                                  |                     |
  |                                  |       ROWS          |
  |                                  |<--------------------|
  |                                  |                     |
  |<---------------------------------|                     |

If you execute the same query often (or a similar query with different column values), consider a prepared statement instead.

Creating an instance¶

The driver provides various ways to create simple statements instances. First, SimpleStatement has a few static factory methods:

SimpleStatement statement =
    SimpleStatement.newInstance(
        "SELECT value FROM application_params WHERE name = 'greeting_message'");

You can then use setter methods to configure additional options. Note that, like all statement implementations, simple statements are immutable, so these methods return a new instance each time. Make sure you don’t ignore the result:

// WRONG: ignores the result
statement.setIdempotent(true);

// Instead, reassign the statement every time:
statement = statement.setIdempotent(true);

If you have many options to set, you can use a builder to avoid creating intermediary instances:

SimpleStatement statement =
    SimpleStatement.builder("SELECT value FROM application_params WHERE name = 'greeting_message'")
        .setIdempotence(true)
        .build();

Finally, Session provides a shorthand method when you only have a simple query string:

session.execute("SELECT value FROM application_params WHERE name = 'greeting_message'");

Using values¶

Instead of hard-coding everything in the query string, you can use bind markers and provide values separately:

  • by position:

    SimpleStatement.builder("SELECT value FROM application_params WHERE name = ?")
        .addPositionalValues("greeting_message")
        .build();
    
  • by name:

    SimpleStatement.builder("SELECT value FROM application_params WHERE name = :n")
        .addNamedValue("n", "greeting_message")
        .build();
    

This syntax has a few advantages:

  • if the values come from some other part of your code, it looks cleaner than doing the concatenation yourself;

  • you don’t need to translate the values to their string representation. The driver will send them alongside the query, in their serialized binary form.

The number of values must match the number of placeholders in the query string, and their types must match the database schema. Note that the driver does not parse simple statements, so it cannot perform those checks on the client side; if you make a mistake, the query will be sent anyway, and the server will reply with an error, that gets translated into a driver exception:

session.execute(
    SimpleStatement.builder("SELECT value FROM application_params WHERE name = :n")
        .addPositionalValues("greeting_message", "extra_value")
        .build());
// Exception in thread "main" com.datastax.oss.driver.api.core.servererrors.InvalidQueryException: 
// Invalid amount of bind variables

Type inference¶

Another consequence of not parsing query strings is that the driver has to guess how to serialize values, based on their Java type (see the default type mappings). This can be tricky, in particular for numeric types:

// schema: create table bigints(b bigint primary key)
session.execute(
    SimpleStatement.builder("INSERT INTO bigints (b) VALUES (?)")
        .addPositionalValues(1)
        .build());
// Exception in thread "main" com.datastax.oss.driver.api.core.servererrors.InvalidQueryException:
// Expected 8 or 0 byte long (4)

The problem here is that the literal 1 has the Java type int. So the driver serializes it as a CQL int (4 bytes), but the server expects a CQL bigint (8 bytes). The fix is to specify the correct Java type:

session.execute(
    SimpleStatement.builder("INSERT INTO bigints (b) VALUES (?)")
        .addPositionalValues(1L) // long literal
        .build());

Similarly, strings are always serialized to varchar, so you could have a problem if you target an ascii column:

// schema: create table ascii_quotes(id int primary key, t ascii)
session.execute(
    SimpleStatement.builder("INSERT INTO ascii_quotes (id, t) VALUES (?, ?)")
        .addPositionalValues(1, "Touché sir, touché...")
        .build());
// Exception in thread "main" com.datastax.oss.driver.api.core.servererrors.InvalidQueryException:
// Invalid byte for ascii: -61

In that situation, there is no way to hint at the correct type. Fortunately, you can encode the value manually as a workaround:

TypeCodec<Object> codec = session.getContext().getCodecRegistry().codecFor(DataTypes.ASCII);
ByteBuffer bytes =
    codec.encode("Touché sir, touché...", session.getContext().getProtocolVersion());

session.execute(
    SimpleStatement.builder("INSERT INTO ascii_quotes (id, t) VALUES (?, ?)")
        .addPositionalValues(1, bytes)
        .build());

Or you could also use prepared statements, which don’t have this limitation since parameter types are known in advance.

PREVIOUS
Prepared statements
NEXT
Temporal types
  • 4.12.0.x
    • 4.13.0.x
    • 4.12.0.x
    • 4.11.1.x
    • 4.10.0.x
    • 4.7.2.x
    • 3.11.2.x
    • 3.11.0.x
    • 3.10.2.x
    • 3.7.2.x
  • Java Driver for Scylla and Apache Cassandra®
  • API Documentation
  • Manual
    • API conventions
    • Case sensitivity
    • Core driver
      • Address resolution
      • Asynchronous programming
      • Authentication
      • Bill of Materials (BOM)
      • Compression
      • Configuration
        • Reference configuration
      • Control connection
      • Custom codecs
      • Detachable types
      • Query idempotence
      • Integration
      • Load balancing
      • Logging
      • Metadata
        • Node metadata
        • Schema metadata
        • Token metadata
      • Metrics
      • Native protocol
      • Non-blocking programming
      • Paging
      • Performance
      • Connection pooling
      • Query timestamps
      • Reactive Style Programming
      • Reconnection
      • Request tracker
      • Retries
      • Using the shaded JAR
      • Speculative query execution
      • SSL
      • Statements
        • Batch statements
        • Per-query keyspace
        • Prepared statements
        • Simple statements
      • Temporal types
      • Request throttling
      • Query tracing
      • Tuples
      • User-defined types
    • Developer docs
      • Administrative tasks
      • Common infrastructure
        • Concurrency
        • Driver context
        • Event bus
      • Native protocol layer
      • Netty pipeline
      • Request execution
    • Mapper
      • Integration
        • Kotlin
        • Lombok
        • Java 14 Records
        • Scala
      • DAOs
        • Custom result types
        • Delete methods
        • GetEntity methods
        • Increment methods
        • Insert methods
        • Null saving strategy
        • Query methods
        • Query provider methods
        • Select methods
        • SetEntity methods
        • Statement attributes
        • Update methods
      • Entities
      • Mapper interface
    • OSGi
    • Query builder
      • Conditions
      • DELETE
      • Idempotence in the query builder
      • INSERT
      • Relations
      • Schema builder
        • Aggregate
        • Function
        • Index
        • Keyspace
        • Materialized View
        • Table
        • Type
      • SELECT
      • Terms
      • TRUNCATE
      • UPDATE
  • Upgrade guide
  • Frequently asked questions
  • Changelog
  • Create an issue
  • Edit this page

On this page

  • Simple statements
    • Quick overview
    • Creating an instance
    • Using values
    • Type inference
Logo
Docs Contact Us About Us
Mail List Icon Slack Icon
© 2022, ScyllaDB. All rights reserved.
Last updated on 25 May 2022.
Powered by Sphinx 4.3.2 & ScyllaDB Theme 1.2.2