如何使用Golang在SQL中执行IN查找?

Go对于此SQL查询中的第二个参数想要什么。我正在尝试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);

回答:

查询只是使用varargs来替换sql中的参数,因此,在您的示例中,您只需要执行

rows, err := stmt.Query(10)

例如,这个和第二个示例的内容是动态的,那么您将

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”部分具有可变的args,则可以执行(播放)

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查找? 的全部内容, 来源链接: utcz.com/qa/427295.html

回到顶部