如何使用sqlx在切片中查询mysql? [英] How to use sqlx to query mysql IN a slice?

查看:136
本文介绍了如何使用sqlx在切片中查询mysql?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在mysql数据库中查询表 IN 切片:

I want to query a table in mysql database for values IN a slice:

var qids []int
//fill qids dynamically
err = database.SQL.Select(&quotes,
    "SELECT * FROM quote WHERE qid IN $1", qids)
if err != nil {
    log.Println(err)
}

但我得到这个错误:

But I get this error:

sql: converting Exec argument #0's type: unsupported type []int, a slice
quotes []

我该如何解决这个问题?

How can I fix this?

推荐答案

sqlx有一个很好的帮手: In()中,我们只需要准备以参数和Rebind为参数的查询,如下所示:

sqlx has a great helper for that: In() we just have to prepare the query taking the args and Rebind, like this:

var qids []int
// fill qids dynamically

query, args, err := sqlx.In("SELECT * FROM quote WHERE qid IN (?)", qids)
if err != nil {
    log.Println(err)
}

// sqlx.In returns queries with the `?` bindvar, we can rebind it for our backend
//
query = database.SQL.Rebind(query)  // database.SQL should be a *sqlx.DB

err = database.SQL.Select(&quotes, query, args...)
if err != nil {
    log.Println(err)
}

另外我建议你看看这里: http://jmoiron.github.io/sqlx/ 有很多例子,包括 IN

Also I recommend you take a look here: http://jmoiron.github.io/sqlx/ there're a lot of examples including IN

这篇关于如何使用sqlx在切片中查询mysql?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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