Skip to content

Instantly share code, notes, and snippets.

@ara-ta3
Last active July 17, 2019 00:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ara-ta3/aeea309598e4844241125761d1169ac1 to your computer and use it in GitHub Desktop.
Save ara-ta3/aeea309598e4844241125761d1169ac1 to your computer and use it in GitHub Desktop.
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",
),
)
}
@marti1125
Copy link

thanks for your example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment