Golang MySQL使用IN运算符查询未定义数量的args
I'm trying to use a MySQL query using the IN operator with undefined amount of arguments into my Golang project.
I'm using the package github.com/go-sql-driver/mysql
and tried to build my solution on this Stackoverflow answer : How to execute an IN lookup in SQL using Golang?
I've read some similar posts giving me some advices about the way to go, but I'm stuck on the execution part of the query, because it does not allow the direct use of a slice as argument.
//converting my form args []string into []int
var args []int
for _, v := range r.Form["type"] {
t, _ := strconv.Atoi(v)
args = append(args, t)
}
sql := "SELECT id, name FROM resources WHERE id IN (SELECT resource_id FROM resources_types WHERE type_id IN (?" + strings.Repeat(",?", len(args)-1) + "))"
fmt.Println("Query : ", sql)
stmt, _ := db.Prepare(sql)
rows, err := stmt.Query(args)
defer stmt.Close()
Golang returns me an error at execution :
Query : SELECT id, name FROM resources WHERE id IN (SELECT resource_id FROM resources_types WHERE type_id IN (?,?)) "sql: statement expects 2 inputs; got 1"
It works when I try with
rows, err := stmt.Query(args[0], args[1])
But as I need an undefined number of arguments, it isn't a solution. Is it at least possible to get it working with MySQL ?
我正在尝试使用带有IN运算符的MySQL查询,并在我的Golang项目中使用未定义的参数数量。
我正在使用软件包 我读过一些类似的文章,为我提供了一些建议,但是我被困在查询的执行部分,因为它确实 p>
Golang在执行时向我返回错误: p>
查询:SELECT ID,名称
“ sql:语句需要2个输入;从FROM资源的ID IN输入(选择resource_id
FROM resources_types的type_id IN(?,?))。 得到了1“ p>
blockquote>
当我尝试 p>
但是由于我需要数量不确定的参数,因此这不是解决方案,至少有可能获得 它可以与MySQL一起使用吗? p>
div> github.com/go-sql-driver/mysql code>,并尝试在此Stackoverflow答案上构建我的解决方案:如何使用SQL在SQL中执行IN查找 Golang吗? p>
//将我的形式args []字符串转换为_,v的[] int
var args [] int
: =范围r.Form [“ type”] {
t,_:= strconv.Atoi(v)
args = append(args,t)
}
sql:=“选择ID,在资源中命名 id IN(从resources_types中选择resource_id,在哪里type_id IN(?“ + strings.Repeat(” ,?“,len(ar gs)-1)+“))”
fmt.Println(“ Query:”,sql)
stmt,_:= db.Prepare(sql)
rows,err:= stmt.Query(args)
defer stmt。 Close()
code> pre>
行,错误:= stmt.Query(args [0],args [1])
code> pre>
Stmt.Query()
has a variadic parameter:
func (s *Stmt) Query(args ...interface{}) (*Rows, error)
This means you can use the ellipsis ...
to pass a slice value as the value of the variadic parameter, but that slice must be of type []interface{}
, e.g.:
var args []interface{}
for _, v := range r.Form["type"] {
t, _ := strconv.Atoi(v)
args = append(args, t)
}
// ...
rows, err := stmt.Query(args...)
As an alternative, you could pre-build the SQL query and execute without passing query arguments, for an example see Go and IN clause in Postgres.