Go Cassandra : Simple CRUD example with Go, Cassandra & GOCQL

We will be creating CRUD application with the help of Go and Cassandra


Using GoCQL driver, Go application connects with Cassandra database. In this example we will be creating CRUD application with the help of Go and Cassandra. To run this example you should have Cassandra instance running on your machine.  
. . .

Create keyspace and table in Cassandra

Create emps table in database using cql client. In this example, we have created test as a keyspace however you can use any other name. You can use cqlsh toll for creating this:


. . .

Install GoCQL driver

To get GoCQL, use following command to install GoCQL driver
go get github.com/gocql/gocql

. . .

Database connection

We are going to create simple console application. So open any text editor and create a file db.go with Emp Struct and following methods
init() – contains code to establish connection with Cassandra database. main() – contains code to run the application.


. . .

Create Employee

Create function createEmp to create a new row in emps table
func createEmp(emp Emp) {
fmt.Println(" **** Creating new emp ****\n", emp)
if err := Session.Query("INSERT INTO emps(empid, first_name, last_name, age) VALUES(?, ?, ?, ?)",
emp.id, emp.firstName, emp.lastName, emp.age).Exec(); err != nil {
fmt.Println("Error while inserting Emp")
fmt.Println(err)
}
}

Get All Employees

function to get All employees from database. We are using iterator with mapScan() to get all employees.
func getEmps() []Emp {
fmt.Println("Getting all Employees")
var emps []Emp
m := map[string]interface{}{}

iter := Session.Query("SELECT * FROM emps").Iter()
for iter.MapScan(m) {
emps = append(emps, Emp{
id: m["empid"].(string),
firstName: m["first_name"].(string),
lastName: m["last_name"].(string),
age: m["age"].(int),
})
m = map[string]interface{}{}
}

return emps
}

Update a Employee

Update a employee based on empid.
func updateEmp(emp Emp) {
fmt.Printf("Updating Emp with id = %s\n", emp.id)
if err := Session.Query("UPDATE emps SET first_name = ?, last_name = ?, age = ? WHERE empid = ?",
emp.firstName, emp.lastName, emp.age, emp.id).Exec(); err != nil {
fmt.Println("Error while updating Emp")
fmt.Println(err)
}
}

Delete a Employee

Delete employee using empid.
func deleteEmp(id string) {
fmt.Printf("Deleting Emp with id = %s\n", id)
if err := Session.Query("DELETE FROM emps WHERE empid = ?", id).Exec(); err != nil {
fmt.Println("Error while deleting Emp")
fmt.Println(err)
}
}

Main method to run the application

. . .
Stay tuned for more tutorials and examples !

Never miss a post from Aditya Agrawal, when you sign up for Ednsquare.