一尘不染

如何使用sqlx在切片中查询mysql?

go

我想查询mysql数据库中的表以获取IN切片值:

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)
}

但是我得到这个错误:

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

我怎样才能解决这个问题?


阅读 268

收藏
2020-07-02

共1个答案

一尘不染

sqlx为此提供了很好的帮助:在In()中,我们只需要使用args和Rebind准备查询,如下所示:

var qids []int

// fills qids on query dynamically
query, args, err := sqlx.In("SELECT * FROM quote WHERE qid IN (?)", qids)
if err != nil {
    log.Fatal(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.Fatal(err)
}

// or just in one line:

err = database.SQL.Select(&quotes, database.SQL.Rebind(query), args...)

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

2020-07-02