如何使用 Golang 在 SQL 中执行 IN 查找? [英] How to execute an IN lookup in SQL using Golang?

查看:31
本文介绍了如何使用 Golang 在 SQL 中执行 IN 查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go 想要这个 SQL 查询中的第二个参数是什么.我正在尝试在 postgres 中使用 IN 查找.

What does Go want for the second param in this SQL query. I am trying to use the IN lookup in postgres.

stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id= $1 AND other_field IN $2")
rows, err := stmt.Query(10, ???)

我真正想要的:

SELECT * FROM awesome_table WHERE id=10 AND other_field IN (this, that);

推荐答案

Query 只需要 varargs 来替换 sql 中的参数所以,在你的例子中,你会做

Query just takes varargs to replace the params in your sql so, in your example, you would just do

rows, err := stmt.Query(10)

比如说,你第二个例子的这个和那个是动态的,然后你会做

say, this and that of your second example were dynamic, then you'd do

stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id=$1 AND other_field IN ($2, $3)")
rows, err := stmt.Query(10,"this","that")

如果IN"部分有可变参数,则可以执行 (play)

If you have variable args for the "IN" part, you can do (play)

package main

import "fmt"
import "strings"

func main() {
    stuff := []interface{}{"this", "that", "otherthing"}
    sql := "select * from foo where id=? and name in (?" + strings.Repeat(",?", len(stuff)-1) + ")"
    fmt.Println("SQL:", sql)
    args := []interface{}{10}
    args = append(args, stuff...)
    fakeExec(args...)
    // This also works, but I think it's harder for folks to read
    //fakeExec(append([]interface{}{10},stuff...)...)
}

func fakeExec(args ...interface{}) {
    fmt.Println("Got:", args)
}

这篇关于如何使用 Golang 在 SQL 中执行 IN 查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆