0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

sqlxのNamedQueryをIN句に適用する方法(名前付きクエリ)

Last updated at Posted at 2020-06-23

1. はじめに

GoのsqlxでSQLを書く際に、IN句にNamedQueryを使おうとしてハマったので簡単な例文を書きます。
例はPostgreSQLで書いてます。

2. 例文

コネクション生成

db, err := sqlx("postgres","接続情報")
if err != nil {
    log.Fatal(err)
}

NamedQuery→PreparedStatementまでの変換

baseQuery := `SELECT * FROM users WHERE id IN (:userID) AND name = :userName`

bindParams := make(map[string]interface{})
bindParams["userID"] = []int{1, 2}
bindParam["userName"] = "Taro"
users := &User{}

query, params, err := sqlx.Named(baseQuery, bindParams)
if err != nil {
    log.Fatal(err)
}
fmt.Println(query)
// SELECT * FROM users WHERE user_id IN (?) AND name = ?
fmt.Println(params)
// [[1 2] Taro] 

sqlxのIn関数で、IN句の展開

query, params, err = sqlx.In(query, params...)
if err != nil {
    log.Fatal(err)
}
fmt.Println(query)
// SELECT * FROM users WHERE user_id IN (?, ?) AND name = ?
fmt.Println(params)
// [1 2 Taro] 

DBドライバーに合わせてバインドし直す

query = db.Rebind(query)
fmt.Println(query)
// SELECT * FROM users WHERE user_id IN ($1, $2) AND name = $3
fmt.Println(params)
// [1 2 Taro] 

SQLを実行し、結果をUser構造体にバインド

err = db.Select(&users, query, params...)
if err != nil {
	log.Fatal(err)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?