Golang加入数组接口 [英] Golang Join array interface

查看:744
本文介绍了Golang加入数组接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建批量插入。我使用gorm github.com/jinzhu/gorm

  import(
fmt
dBgithub.com/edwinlab/api/repositories


func更新()错误{
tx:= dB.GetWriteDB()。Begin()
sqlStr:=INSERT INTO city(code,name)VALUES(?,?),(?,?)
vals:= [] interface {} {}
$ b $ vals = append(vals,XX1,Jakarta)
vals = append(vals,XX2, 万隆)

tx.Exec(sqlStr,vals)

tx.Commit()

返回零
}

但是我收到了一个错误:


错误1136:列计数与第1行的值计数不匹配因为我返回错误的查询

  INSERT INTO (代码,名称)VALUES('XX1','雅加达','XX2','万隆',%!v(MISSING)),(%!v(MISSING),%!v(MISSING))


如果我使用手动查询, (b)

$ $ $ $ $ c $ t $ t $。$ e $ code>

它会生成:

  INSERT INTO city(code,name)VALUES('XX1','Jakarta'),('XX2','Bandung')

问题是如何让数组接口生成像XX1,Jakarta,...



感谢您的帮助。

解决方案

如果您想将切片的元素传递给函数使用variadic参数,你必须使用 ... 来告诉编译器你想单独传递所有元素,而不是把slice值作为单个参数传递,所以简单地做:

  tx.Exec(sqlStr,vals ...)

详细规格如下:将参数传递给...参数



Tx.Exec() 的签名为:



p $ func(tx * Tx)Exec(query string,args ... interface {})(result,error)

所以你必须传递 vals ... 。也不要忘记检查返回的错误,例如:

  res,err:= tx.Exec(sqlStr,vals .. )
if err!= nil {
//处理错误
}


I try to create bulk insert. I use 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
}

But I got an error:

Error 1136: Column count doesn't match value count at row 1 becuse i return wrong query

INSERT INTO city(code, name) VALUES ('XX1','Jakarta','XX2','Bandung', %!v(MISSING)),(%!v(MISSING), %!v(MISSING))

If I use manual query it works:

tx.Exec(sqlStr, "XX1", "Jakarta", "XX2", "Bandung")

It will generate:

INSERT INTO city(code, name) VALUES ('XX1', 'Jakarta'),('XX2', 'Bandung')

The problem is how to make array interface to generate string like "XX1", "Jakarta", ...

Thanks for help.

解决方案

If you want to pass elements of a slice to a function with variadic parameter, you have to use ... to tell the compiler you want to pass all elements individually and not pass the slice value as a single argument, so simply do:

tx.Exec(sqlStr, vals...)

This is detailed in the spec: Passing arguments to ... parameters.

Tx.Exec() has the signature of:

func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)

So you have to pass vals.... Also don't forget to check returned error, e.g.:

res, err := tx.Exec(sqlStr, vals...)
if err != nil {
    // handle error
}

这篇关于Golang加入数组接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆