Skip to content

Instantly share code, notes, and snippets.

@kmuthukk
Created September 22, 2019 15:34
Show Gist options
  • Save kmuthukk/f182837117f7af553a0d500c54e89ee3 to your computer and use it in GitHub Desktop.
Save kmuthukk/f182837117f7af553a0d500c54e89ee3 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"time"
"github.com/gocql/gocql"
)
func main() {
// Connect to the cluster.
cluster := gocql.NewCluster("127.0.0.1")
// Use the same timeout as the Java driver.
cluster.Timeout = 12 * time.Second
// Create the session.
session, _ := cluster.CreateSession()
defer session.Close()
// Set up the keyspace and table.
if err := session.Query("CREATE KEYSPACE IF NOT EXISTS ybdemo").Exec(); err != nil {
log.Fatal(err)
}
fmt.Println("Created keyspace ybdemo")
if err := session.Query(`DROP TABLE IF EXISTS ybdemo.employee`).Exec(); err != nil {
log.Fatal(err)
}
var createStmt = `CREATE TABLE ybdemo.employee (id int, name varchar,
age int,
language varchar,
PRIMARY KEY(id)) WITH default_time_to_live = 5;`
if err := session.Query(createStmt).Exec(); err != nil {
log.Fatal(err)
}
fmt.Println("Created table ybdemo.employee")
// Insert into the table.
for i := 0; i < 5; i++ {
insertStmt := fmt.Sprintf("INSERT INTO ybdemo.employee(id, name, age, language) VALUES (%d, 'John+%d', %d, 'Go')", i+1, i+1, ((i+500)%20)+1)
if err := session.Query(insertStmt).Exec(); err != nil {
log.Fatal(err)
}
fmt.Printf("Inserted data: %s\n", insertStmt)
}
fmt.Printf("Sleeping 6 seconds\n");
time.Sleep(6 * time.Second);
// Read from the table.
var name string
var age int
var language string
iter := session.Query(`SELECT name, age, language FROM ybdemo.employee WHERE id = 1`).Consistency(gocql.One).Iter()
fmt.Printf("Query for id=1 returned: ")
for iter.Scan(&name, &age, &language) {
fmt.Printf("Row[%s, %d, %s]\n", name, age, language)
}
fmt.Printf("\n")
if err := iter.Close(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment