Home > Software engineering >  How to form dynamic insert query for cassandra golang
How to form dynamic insert query for cassandra golang

Time:05-10

I have been trying to create a dynamic query in golang for cassandra using gocql driver ,this is what I tried so far

func WriteRecord(session gocql.Session, insertstring string, table string, fields []string, values ...interface{}) error {
    var placeholder []string

    for range fields {
        placeholder = append(placeholder, "?")
    }
    querystring := fmt.Sprintf(insertstring, table, strings.Join(fields, ", "), strings.Join(placeholder, ", "))
    fmt.Println(querystring)
    return session.Query(querystring, values...).Exec()
}

And calling this method in this

func writeData(session gocql.Session) {
    fields := []string{
        "id",
        "message",
    }

    for i := 1; i <= 10; i   {
        /*
            if err := session.Query(
                "INSERT INTO example_keyspace.example_go (id, message) VALUES (?, ?)", i, "Hello from golang!",
            ).Exec(); err != nil {
                log.Fatal(err)
            }
        */
        insertString := "INSERT INTO example_keyspace.%s(%s,%s) VALUES (%s,%s)"
        err := WriteRecord(session, insertString, "kafka", fields, i, "hey kafka")
        if err != nil {
            log.Fatal(err)
        }

    }
}

its giving me this output

INSERT INTO example_keyspace.kafka(id, message,?, ?) VALUES (%!s(MISSING),%!s(MISSING))

How to fix this problem ,I am not sure where I am doing wrong

CodePudding user response:

You are almost right just small modifications in your formatted insertstring ,see below

func WriteRecord(session gocql.Session, insertstring string, table string, fields []string, values ...interface{}) error {
    var placeholder []string

    for range values {
        placeholder = append(placeholder, "?")
    }
    querystring := fmt.Sprintf(insertstring, table, strings.Join(fields, ", "), strings.Join(placeholder, ", "))
    fmt.Println(querystring)
    return session.Query(querystring, values...).Exec()
}



func writeData(session gocql.Session) {
    fields := []string{
        "id",
        "message",
    }

    for i := 1; i <= 10; i   {
        /*
            if err := session.Query(
                "INSERT INTO example_keyspace.example_go (id, message) VALUES (?, ?)", i, "Hello from golang!",
            ).Exec(); err != nil {
                log.Fatal(err)
            }
        */
        insertString := "INSERT INTO example_keyspace.%s(%s) VALUES (%s)"
        err := WriteRecord(session, insertString, "kafka", fields, i, "hey kafka") // Just remove extra %s as you are joining the string 
        if err != nil {
            log.Fatal(err)
        }

    }
}

the final insertstring output you would get is

INSERT INTO example_keyspace.kafka(id, message) VALUES (?, ?)

And as per this line

return session.Query(querystring, values...).Exec() // the  values will be passed

Hope it helps

  • Related