dousong9729 2013-05-18 18:29
浏览 156

如何在Go中进行IN查询?

I'd like to run a query like this in Go using "database/sql" package:

SELECT id, name FROM users WHERE id IN (1,2,3,4);

How do I use variable substitution in the query command? E.g., I want to do this (which of course doesn't work):

db.Query("SELECT id, name FROM users WHERE id IN (?)", []int{1,2,3,4})
  • 写回答

1条回答 默认 最新

  • dongmu4591 2013-05-19 07:56
    关注

    @Volker suggests in the comments that some database drivers may be able to expand the slice for you. Any driver can handle the slice elements individually, however:

    db.Query("SELECT id, name FROM users WHERE id IN (?, ?, ?, ?)", 1, 2, 3, 4)
    

    Of course, you'd need to know exactly how many elements are going to be in the slice when you write that, which probably isn't the case. Generating the correct number of question marks is simple enough and gives you a general solution:

    ints := []interface{}{1,2,3,4}
    marks := strings.Repeat("?,", len(ints) - 1) + "?"
    db.Query("SELECT id, name FROM users WHERE id IN (" + marks + ")", ints...)
    

    If your slice might be empty, you'll have to handle that somehow.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度