How to execute an IN lookup in SQL using Golang?

前端 未结 9 942
余生分开走
余生分开走 2020-12-01 02:12

What does Go want for the second param in this SQL query. I am trying to use the IN lookup in postgres.

stmt, err := db.Prepare(\"SELECT * FRO         


        
9条回答
  •  萌比男神i
    2020-12-01 02:26

    It looks like you may be using the pq driver. pq recently added Postgres-specific Array support via pq.Array (see pull request 466). You can get what you want via:

    stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id= $1 AND other_field = ANY($2)")
    rows, err := stmt.Query(10, pq.Array([]string{'this','that'})
    

    I think this generates the SQL:

    SELECT * FROM awesome_table WHERE id=10 AND other_field = ANY('{"this", "that"}');
    

    Note this utilizes prepared statements, so the inputs should be sanitized.

提交回复
热议问题