本文介绍了golang - mysql一次插入多个数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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},
}
//我不想这样做
用于_,v:=范围数据{
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:=范围数据{
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)

我需要一个更安全有效的函数来同时插入多个数据。

解决方案

为什么不是这样? (在这里写没有测试,所以可能会出现语法错误):

$ sql $ s $:$ INSERT INTO test(n1,n2,n3 )VALUES
vals = [] interface {} {}

for _,row:=范围数据{
sqlStr + =(?,?,?),
vals = append(vals,row [v1],row [v2],row [v3])
}
//修剪最后的
sqlStr = sqlStr [0:len(sqlStr)-2]
//准备语句
stmt,_:= db.Prepare(sqlStr)

//格式化所有vals立即
res,_:= stmt.Exec(vals ...)


I know that Insert multiple data at once more efficiency:

INSERT INTO test(n1, n2, n3)
VALUES(v1, v2, v3),(v4, v5, v6),(v7, v8, v9);

How to do that in 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"])
}

Use string splice, but it's not good. db.Prepare more safer, right?

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)

I need a function safer and efficient insert mulitple data at once.

解决方案

why not something like this? (writing here without testing so there might be syntax errors):

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)-2]
//prepare the statement
stmt, _ := db.Prepare(sqlStr)

//format all vals at once
res, _ := stmt.Exec(vals...)

这篇关于golang - mysql一次插入多个数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 17:21