我尝试创建批量插入。我使用gorm github.com/jinzhu/gorm
import (
"fmt"
dB "github.com/edwinlab/api/repositories"
)
func Update() error {
tx := dB.GetWriteDB().Begin()
sqlStr := "INSERT INTO city(code, name) VALUES (?, ?),(?, ?)"
vals := []interface{}{}
vals = append(vals, "XX1", "Jakarta")
vals = append(vals, "XX2", "Bandung")
tx.Exec(sqlStr, vals)
tx.Commit()
return nil
}
但我得到一个错误:
错误 1136:列计数与第 1 行的值计数不匹配,因为我返回了错误的查询
INSERT INTO city(code, name) VALUES ('XX1','Jakarta','XX2','Bandung', %!v(MISSING)),(%!v(MISSING), %!v(MISSING))
如果我使用手动查询,它可以工作:
tx.Exec(sqlStr, "XX1", "Jakarta", "XX2", "Bandung")
它将生成:
INSERT INTO city(code, name) VALUES ('XX1', 'Jakarta'),('XX2', 'Bandung')
问题是如何使数组接口生成类似的字符串"XX1", "Jakarta", ...
感谢帮助。