dongmaobeng7145 2016-11-12 17:44
浏览 124
已采纳

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

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?

  • 写回答

3条回答 默认 最新

  • dtpd58676 2016-11-12 21:37
    关注

    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
    
    // 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...)
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题