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
You are almost right just small modifications in your formatted insertstring ,see below
the final insertstring output you would get is
And as per this line
Hope it helps