doudeng2016 2014-01-14 07:32
浏览 32
已采纳

如何一次插入多个数据

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.

  • 写回答

3条回答 默认 最新

  • doukai1226 2014-01-14 11:15
    关注

    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...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大