Connect with the Java driver
Because Astra DB is based on Apache Cassandra®, you can use Cassandra drivers to connect to your Astra DB Classic databases.
To use the Java driver, you need to add the driver dependency to your pom.xml, use the ConnectDatabase class to initialize the driver, and then connect the driver to your Astra DB Classic database.
Once connected, your scripts can use the driver to run commands against your database.
Prerequisites
-
Install Maven.
-
Install a current Java version.
-
Download your database’s Secure Connect Bundle (SCB).
For multi-region databases, download the Secure Connect Bundle (SCB) for a region that is geographically close to your application to reduce latency.
If you need to connect to multiple regions in the same application, you need the Secure Connect Bundle (SCB) for each region, and your driver code must instantiate one root object (
session) for each region. For more information, see Best practices for Cassandra drivers. -
Set the following environment variables:
-
ASTRA_DB_ID: The database ID. -
ASTRA_DB_KEYSPACE: A keyspace in your database, such asdefault_keyspace. -
ASTRA_DB_APPLICATION_TOKEN: An application token with the Database Administrator role.
-
Driver authentication methods
There are two driver authentication methods: token authentication, or clientId and secret authentication.
-
Token authentication
-
Client ID and secret authentication
This authentication method is supported and recommended for most recent driver versions.
In your driver authentication code, pass the literal string token as the username and your application token value (AstraCS:…) as the password.
For example:
("token", "AstraCS:...")
If you are on an older driver version that doesn’t support token authentication, then you might need to use clientId and secret.
When you generate an application token, download or copy the token.json that contains the following values:
{
"clientId": "CLIENT_ID",
"secret": "CLIENT_SECRET",
"token": "APPLICATION_TOKEN"
}
In your driver authentication code, pass clientId as the username and secret as the password.
For example:
("CLIENT_ID", "SECRET")
For more information, see Token details.
Add the Java driver dependency
-
In your project’s
pom.xmlfile, add a dependency for the Apache Cassandra Java driver.
-
Latest version
-
Version 4.17 and earlier
<dependency> <groupId>org.apache.cassandra</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency><dependency> <groupId>com.datastax.oss</groupId> <artifactId>java-driver-core</artifactId> <version>LATEST_VERSION</version> </dependency>If you choose to install an earlier version, make sure you choose a version that is compatible with Astra DB. For more information, see Cassandra drivers supported by DataStax.
-
Initialize and connect the Java driver
-
In your Java project, navigate to
/src/main/java, and then create aConnectDatabase.javafile:cd JAVA_PROJECT_DIRECTORY/src/main/java touch ConnectDatabase.java -
Copy the following code into
ConnectDatabase.java, and then replacePATH/TO/SCB.zipwith the absolute path to your database’s Secure Connect Bundle (SCB) (secure-connect-DATABASE_NAME.zip):ConnectDatabase.javaimport com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.cql.ResultSet; import com.datastax.oss.driver.api.core.cql.Row; import java.nio.file.Paths; public class ConnectDatabase { public static void main(String[] args) { // Create the CqlSession object: try (CqlSession session = CqlSession.builder() .withCloudSecureConnectBundle(Paths.get("PATH/TO/SCB.zip")) .withAuthCredentials("token", System.getenv("ASTRA_DB_APPLICATION_TOKEN")) .withKeyspace(System.getenv("ASTRA_DB_KEYSPACE")) .build()) { // Select the release_version from the system.local table: ResultSet rs = session.execute("select release_version from system.local"); Row row = rs.one(); //Print the results of the CQL query to the console: if (row != null) { System.out.println(row.getString("release_version")); } else { System.out.println("An error occurred."); } } System.exit(0); } }This code imports dependencies, initializes the Java driver, implements the
ConnectDatabaseclass to connect to your Astra DB database, runs a CQL query, and then prints the output to the console. -
Save
ConnectDatabase.javaand then build your Maven project.The console output prints the
release_versionvalue from thesystem.localtable in your Astra DB database. -
Extend or modify this script to run other commands against your database or connect to other databases. For more information, see the Apache Cassandra Java driver documentation and DataStax-compatible Cassandra drivers.
Connect the Java Cloud driver (deprecated)
|
The legacy Stargate APIs and their associated drivers are deprecated for Astra DB Classic as of September 2024, and end-of-life (EOL) is scheduled for the end of 2025. As EOL approaches, DataStax will provide migration information to support your transition to other options. If you have questions or concerns, contact your account representative or DataStax Support. |
Connect the grpc-proto driver (deprecated)
-
Generate a Bearer Token with the Database Administrator role.
-
Install a Java Development Kit (SDK) and Maven.
-
Create a keyspace.
-
Create a table for your keyspace.
-
Add the Java Cloud driver dependencies to your
pom.xmlfile. Make sure the dependency names correspond to the installed versions.Replace
PROTO_VERSIONwith the current gRPC proto version, and replace
NETTY_VERSIONwith the current gRPC netty version.
<dependencies> <dependency> <groupId>io.stargate.grpc</groupId> <artifactId>grpc-proto</artifactId> <version>PROTO_VERSION</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty-shaded</artifactId> <version>NETTY_VERSION</version> </dependency> </dependencies> -
While running Stargate on Astra DB, create a connection. To connect to your Stargate instance, create the client. For example, for a local Stargate instance, the following client code fetches an authentication token with a REST call:
private static final String ASTRA_DB_ID = "DATABASE_ID"; private static final String ASTRA_DB_REGION = "REGION_NAME"; private static final String ASTRA_TOKEN = "APPLICATION_TOKEN"; private static final String ASTRA_KEYSPACE = "KEYSPACE_NAME"; public static void main(String[] args) throws Exception { //------------------------------------- // 1. Initializing Connectivity //------------------------------------- ManagedChannel channel = ManagedChannelBuilder .forAddress(ASTRA_DB_ID + "-" + ASTRA_DB_REGION + ".apps.astra.datastax.com", 443) .useTransportSecurity() .build(); // blocking stub version StargateGrpc.StargateBlockingStub blockingStub = StargateGrpc.newBlockingStub(channel) .withDeadlineAfter(10, TimeUnit.SECONDS) .withCallCredentials(new StargateBearerToken(ASTRA_TOKEN)); } -
Perform a query by passing a CQL query to the client using the
ExecuteQuery()function for standard query execution:QueryOuterClass.Response queryString = blockingStub.executeQuery(QueryOuterClass .Query.newBuilder() .setCql("SELECT firstname, lastname FROM " + ASTRA_KEYSPACE + ".users") .build()); -
To use a batch statement, provide an
ExecuteBatch()function to execute a batch query:blockingStub.executeBatch( QueryOuterClass.Batch.newBuilder() .addQueries( QueryOuterClass.BatchQuery.newBuilder() .setCql("INSERT INTO " + ASTRA_KEYSPACE + ".users (firstname, lastname) VALUES('Jane', 'Doe')") .build()) .addQueries( QueryOuterClass.BatchQuery.newBuilder() .setCql("INSERT INTO " + ASTRA_KEYSPACE + ".users (firstname, lastname) VALUES('Serge', 'Provencio')") .build()) .build()); System.out.println("2 rows have been inserted in table users.");