Golang Join array interface

I am trying to create a volume insert. I am using 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 have an error:

Error 1136: The number of columns does not match the number of values ​​in row 1 because I am returning an invalid 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 an array interface to create a string, for example "XX1", "Jakarta", ...

Thanks for the help.

+5
source share
1 answer

If you want to pass slice elements to a function with a variable parameter, you should use ... to tell the compiler that you want to pass all the elements individually and not pass the slice value as one argument, so just do:

 tx.Exec(sqlStr, vals...) 

This is described in detail in the specification: Passing arguments ... parameters .

Tx.Exec() has the signature:

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

So you have to go through vals... Also do not forget to check the returned error, for example:

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

Source: https://habr.com/ru/post/1245457/


All Articles