sqlx里面的in操作,还是相对比较特殊的,怎么来实现呢?直接上代码,供参考:
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Hoge struct {
ID int `db:"id"`
Name string `db:"name"`
}
func main() {
db, err := connect()
if err != nil {
panic(err)
}
s := "SELECT * FROM hoge WHERE id IN (?)"
q, vs, err := sqlx.In(s, []int{2, 3})
// fmt.Printf("%+v\n", q)
// => SELECT * FROM hoge WHERE id IN (?, ?)
if err != nil {
panic(err)
}
var hs []Hoge
err = db.Select(&hs, q, vs...)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", hs)
// => [{ID:2 Name:fuga} {ID:3 Name:piyo}]
}
func connect() (*sqlx.DB, error) {
return sqlx.Connect(
"mysql",
fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s",
"root",
"",
"localhost",
"3306",
"test",
),
)
}
有疑问加站长微信联系(非本文作者)