LoginSignup
6
1

More than 5 years have passed since last update.

今さら聞けないPlaceholder

Posted at

問題

golangの標準パッケージ "database/sql"を使って、以下のようにPlaceholder付のクエリ書いたら、Syntax errorが発生してしまう、なぜか。

参考
- https://golang.org/pkg/database/sql/#example_DB_Query_multipleResultSets
- https://play.golang.org/p/D-5ZVSzhcXx

func main() {
    age := 27
    q := `
create temp table uid (id bigint); -- Create temp table for queries.
insert into uid
select id from users where age < ?; -- Populate temp table.

-- First result set.
select
    users.id, name
from
    users
    join uid on users.id = uid.id
;

-- Second result set.
select 
    ur.user, ur.role
from
    user_roles as ur
    join uid on uid.id = ur.user
;
    `
    rows, err := db.Query(q, age)
    if err != nil {
        log.Fatal(err) // Syntax error
    }

原因

PostgresDB使ってたため、?を$1に修正すればエラーは解消できる。

プレースホルダ付きのSQLをDBにあらかじめ送信しているため、DBごとに記法が異なる。

スクリーンショット 2019-03-07 17.45.34.png

引用: http://go-database-sql.org/prepared.html

6
1
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
6
1