duanqiang3925 2016-06-26 08:45
浏览 104
已采纳

Postgres中的Go and IN子句

I am trying to execute the following query against the PostgreSQL database in Go using pq driver:

SELECT COUNT(id)
FROM tags
WHERE id IN (1, 2, 3)

where 1, 2, 3 is passed at a slice tags := []string{"1", "2", "3"}.

I have tried many different things like:

s := "(" + strings.Join(tags, ",") + ")"
if err := Db.QueryRow(`
    SELECT COUNT(id)
    FROM tags
    WHERE id IN $1`, s,
).Scan(&num); err != nil {
    log.Println(err)
}

which results in pq: syntax error at or near "$1". I also tried

if err := Db.QueryRow(`
    SELECT COUNT(id)
    FROM tags
    WHERE id IN ($1)`, strings.Join(stringTagIds, ","),
).Scan(&num); err != nil {
    log.Println(err)
}

which also fails with pq: invalid input syntax for integer: "1,2,3"

I also tried passing a slice of integers/strings directly and got sql: converting Exec argument #0's type: unsupported type []string, a slice.

So how can I execute this query in Go?

  • 写回答

2条回答 默认 最新

  • duandun2218 2016-06-26 10:33
    关注

    Pre-building the SQL query (preventing SQL injection)

    If you're generating an SQL string with a param placeholder for each of the values, it's easier to just generate the final SQL right away.

    Note that since values are strings, there's place for SQL injection attack, so we first test if all the string values are indeed numbers, and we only proceed if so:

    tags := []string{"1", "2", "3"}
    buf := bytes.NewBufferString("SELECT COUNT(id) FROM tags WHERE id IN(")
    for i, v := range tags {
        if i > 0 {
            buf.WriteString(",")
        }
        if _, err := strconv.Atoi(v); err != nil {
            panic("Not number!")
        }
        buf.WriteString(v)
    }
    buf.WriteString(")")
    

    Executing it:

    num := 0
    if err := Db.QueryRow(buf.String()).Scan(&num); err != nil {
        log.Println(err)
    }
    

    Using ANY

    You can also use Postgresql's ANY, whose syntax is as follows:

    expression operator ANY (array expression)
    

    Using that, our query may look like this:

    SELECT COUNT(id) FROM tags WHERE id = ANY('{1,2,3}'::int[])
    

    In this case you can declare the text form of the array as a parameter:

    SELECT COUNT(id) FROM tags WHERE id = ANY($1::int[])
    

    Which can simply be built like this:

    tags := []string{"1", "2", "3"}
    param := "{" + strings.Join(tags, ",") + "}"
    

    Note that no check is required in this case as the array expression will not allow SQL injection (but rather will result in a query execution error).

    So the full code:

    tags := []string{"1", "2", "3"}
    
    q := "SELECT COUNT(id) FROM tags WHERE id = ANY($1::int[])"
    param := "{" + strings.Join(tags, ",") + "}"
    
    num := 0
    if err := Db.QueryRow(q, param).Scan(&num); err != nil {
        log.Println(err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line