【问题标题】:golang gorp insert multiple recordsgolang gorp插入多条记录
【发布时间】:2016-09-08 01:43:21
【问题描述】:

使用 gorp 如何高效地插入多条记录?即不是一次插入一个,而是批量插入?

var User struct {
   Name string
   Email string
   Phone string
}
var users []Users
users = buildUsers()
dbMap.Insert(users...) //this fails compilation
//I am forced to loop over users and insert one user at a time. Error Handling omitted for brevity

gorp 有更好的机制吗?驱动是 MySQL。

【问题讨论】:

    标签: go gorp


    【解决方案1】:

    正如我在其他一些资源上发现的那样,这不起作用的原因是 interface{}User{} 在内存中没有相同的布局,因此它们的切片不是兼容的类型。建议的解决方案是在 for 循环中将 []User{} 转换为 []interface{},如下所示:https://golang.org/doc/faq#convert_slice_of_interface

    还有一点需要注意:您需要为DbMap.Insert()function 使用指针。

    我是这样解决的:

    s := make([]interface{}, len(users))
    for i, v := range users {
        s[i] = &v
    }
    err := dbMap.Insert(s...)
    

    注意&v很重要,否则Insert会抱怨非指针。

    【讨论】:

      【解决方案2】:

      看起来 gorp 没有任何东西可以为原始 SQL 或多值插入提供包装器(这始终取决于 SQL 方言)。
      您是否担心速度或交易?如果没有,我只会在 for 循环中进行插入。

      【讨论】:

        猜你喜欢
        • 2015-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-01
        • 2012-09-04
        • 2015-10-04
        • 2017-04-06
        • 1970-01-01
        相关资源
        最近更新 更多