dosf40815 2018-06-01 20:53 采纳率: 100%
浏览 213

SQL + goLang-运行带有IN条件的select语句-并将其传递给ID数组?

I want to perform the following logic -

SELECT some_column
FROM table_name
WHERE id IN (value1, value2, ...);

in my go code I have the following int array to represent my ids :

idsToGet := []int{1,2}

I fully understand that you might normally do a sprintf and pass in the one id you were looking for... BUT...

I feel like there is a sensible way to do this without iterating over the array, and doing this as a separate call for each ID... via sprintf - is there a way I can do this as just one call - and have my IN clause auto contain everything from my array?

Totally new to Go - been trying to solve this for an hour, I have it working for single id's - but not for multiples.

  • 写回答

1条回答 默认 最新

  • douzheyo2617 2018-06-02 02:14
    关注

    You don't want to use Sprintf to put raw values into SQL, that's a bad habit. What you want to do is build a bit of SQL with the right number of placeholders and then let the library take care of replacing the placeholders with their value.

    If you have two ints in your array then you want to build this:

    SELECT some_column
    FROM table_name
    WHERE id IN (?, ?)
    

    If you have four then you want to build:

    SELECT some_column
    FROM table_name
    WHERE id IN (?, ?, ?, ?)
    

    and so on. All you need is a simple function that can produce n placeholders; there are lots of ways to do this:

    func placeholders(n int) string {
        ps := make([]string, n)
        for i := 0; i < n; i++ {
            ps[i] = "?"
        }
        return strings.Join(ps, ",")
    }
    

    or maybe:

    func placeholders(n int) string {
        var b strings.Builder
        for i := 0; i < n - 1; i++ {
            b.WriteString("?,")
        }
        if n > 0 {
            b.WriteString("?")
        }
        return b.String()
    }
    

    or whatever is clearest to you, the implementation is unlikely to have any measurable impact as long as it is correct.

    Then you can say things like:

    query := fmt.Sprintf("select some_column from table_name where id in (%s)", placeholders(len(idsToGet)))
    rows, err := db.Query(query, idsToGet...)
    

    and spin throw rows in the usual manner.

    评论

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP