Prerequisites
- A Cassandra client driver for Java is installed. For more information, see Install and upgrade Cassandra CQL Java Driver.
- The endpoint of an ApsaraDB for Lindorm (Lindorm) cluster is obtained. For more information, see Connect to a Lindorm cluster.
Establish a connection
String[] contactPoints = new String[]{
"ip"// Enter the endpoint of the Lindorm cluster that you want to connect. You can obtain the value in the Lindorm console. This parameter value cannot include a port number.
};
Cluster cluster = Cluster.builder()
.addContactPoints(contactPoints)// Enter the username and the password that you use to connect to the cluster. You can obtain the username and the password in the Lindorm console.
.withAuthProvider(new PlainTextAuthProvider(username, password))
.build();
cluster.init();// Initialize the connection.
Session session = cluster.connect();// Initialize a session. You cannot create a session for each request. We recommend that you create several sessions in advance for each process.
Use a Cassandra client driver for Java to execute statements
Execute data definition language (DDL) statements
// Create a keyspace. Configure a replication strategy and replication factor for the keyspace.
session.execute(
"CREATE KEYSPACE IF NOT EXISTS testKeyspace WITH replication "
+ "= {'class':'SimpleStrategy', 'replication_factor':1};");
// Create a table. Configure a primary key and one or more regular columns for the table. A primary key consists of a partition key and clustering key.
session.execute(
"CREATE TABLE IF NOT EXISTS testKeyspace.testTable ("
+ "id int PRIMARY KEY,"
+ "name text,"
+ "age int,"
+ "address text"
+ ");");
// Clear a table.
session.execute("TRUNCATE TABLE testKeyspace.testTable;");
// Delete a table.
session.execute("DROP TABLE testKeyspace.testTable ");
Execute data manipulation language (DML) statements
// Execute the INSERT statement.
session.execute(
"INSERT INTO testKeyspace.testTable (id, name, age, address) "
+ "VALUES ("
+ "1,"
+ "'testname',"
+ "11,"
+ "'hangzhou');");
// Execute the SELECT statement. If you want to query all the columns in a table, use SELECT *. You can also query specified columns in a table.
ResultSet res = session.execute(
"SELECT * FROM testKeyspace.testTable ;");
// If you want to query each row for a column, execute the following statements:
for (Row row : results)
{
int id = row.getInt("id");
String name = row.getString("name");
int age = row.getInt("age");
String address = row.getString("address");
}
// Close a session.
session.close();
// Disable a cluster.
cluster.close();