我知道一次插入多个数据效率更高:
INSERT INTO test(n1, n2, n3) VALUES(v1, v2, v3),(v4, v5, v6),(v7, v8, v9);
在golang中该怎么做?
data := []map[string]string{ {"v1":"1", "v2":"1", "v3":"1"}, {"v1":"2", "v2":"2", "v3":"2"}, {"v1":"3", "v2":"3", "v3":"3"}, } //I do not want to do it for _, v := range data { sqlStr := "INSERT INTO test(n1, n2, n3) VALUES(?, ?, ?)" stmt, _ := db.Prepare(sqlStr) res, _ := stmt.Exec(v["v1"], v["v2"], v["v3"]) }
使用字符串拼接,但这不是很好。db.Prepare更安全吧?
sqlStr := "INSERT INTO test(n1, n2, n3) VALUES" for k, v := range data { if k == 0 { sqlStr += fmt.Sprintf("(%v, %v, %v)", v["v1"], v["v2"], v["v3"]) } else { sqlStr += fmt.Sprintf(",(%v, %v, %v)", v["v1"], v["v2"], v["v3"]) } } res, _ := db.Exec(sqlStr)
我需要一个功能更安全,更高效的函数,一次插入多个数据。
为什么不这样呢?(在此处编写但未进行测试,因此可能存在语法错误):
sqlStr := "INSERT INTO test(n1, n2, n3) VALUES " vals := []interface{}{} for _, row := range data { sqlStr += "(?, ?, ?)," vals = append(vals, row["v1"], row["v2"], row["v3"]) } //trim the last , sqlStr = sqlStr[0:len(sqlStr)-1] //prepare the statement stmt, _ := db.Prepare(sqlStr) //format all vals at once res, _ := stmt.Exec(vals...)