Cassandra Create Data - Apache Cassandra

What is Cassandra Create Data?

Creating Data using Cqlsh

You can insert data into the columns of a row in a table using the command INSERT. Given underneath is the syntax for creating data in a table.

Instance

Let us assume there is a table called emp with columns (emp_id, emp_name, emp_city, emp_phone, emp_sal) and you have to insert the following data into the emp table.

emp_id

emp_name

emp_city

emp_phone

emp_sal

1

ram

Hyderabad

9848022338

50000

2

robin

Hyderabad

9848022339

40000

3

rahman

Chennai

9848022330

45000

Use the commands given below to fill the table with required data.

Verification

After inserting data, use SELECT statement to verify whether the data has been inserted or not. If you verify the emp table using SELECT statement, it will give you the following output.

Here you can observe the table has populated with the data we inserted.

Creating Data using Java API

You can create data in a table using the execute() method of Session class. Follow the steps given below to create data in a table using java API.

Step1: Create a Cluster Object

Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below.

Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder.

Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object.

You can build a cluster object using a single line of code as shown below.

Step 2: Create a Session Object

Create an instance of Session object using the connect() method of Cluster class as shown below.

This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below.

Here we are using the KeySpace called tp. Therefore, create the session object as shown below.

Step 3: Execute Query

You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh.

In the following example, we are inserting data in a table called emp. You have to store the query in a string variable and pass it to the execute() method as shown below.

Given below is the complete program to insert data into a table in Cassandra using Java API.

Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.

Under normal conditions, it should produce the following output:

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Apache Cassandra Topics