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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 基于52单片机的酒精浓度检测系统加继电器和sim800
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答