duanguzhong5776 2016-08-30 09:34
浏览 392
已采纳

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 ?

  • 写回答

1条回答 默认 最新

  • douyan1972 2016-08-30 09:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效