1 回答
TA贡献1757条经验 获得超7个赞
您几乎是对的,只是对格式化的 insertstring 进行了一些小的修改,请参见下文
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)
}
}
}
您将获得的最终 insertstring 输出是
INSERT INTO example_keyspace.kafka(id, message) VALUES (?, ?)
按照这条线
return session.Query(querystring, values...).Exec() // the values will be passed
希望能帮助到你
- 1 回答
- 0 关注
- 89 浏览
添加回答
举报