Go postgresql LIKE query

前端 未结 3 683
陌清茗
陌清茗 2020-12-14 19:16

I\'m working with Go and PostgreSQL (pq driver), I have the following query

SELECT p.id, p.name, p.description, p.price, p.image, p.rate
FROM products AS p
W         


        
相关标签:
3条回答
  • 2020-12-14 19:31

    According to this issue your query must not contain '%' sign, but "name" parameter must be quoted by '%'

    query := `SELECT p.id, p.name, p.description, p.price, p.image, p.rate
        FROM products AS p
        WHERE LOWER(p.name) LIKE $1 ORDER BY p.rate DESC`
    
    product_rows, err := db.Query(query, fmt.Sprintf("%%%s%%", name))
    
    0 讨论(0)
  • 2020-12-14 19:44

    Dont put qoutes when you are preparing your query. Just provide the value with qoutes and % sign. This will solve the problem. tried and tested.

    Solution: query := SELECT p.id, p.name, p.description, p.price, p.image, p.rate FROM products AS p WHERE LOWER(p.name) LIKE $1 ORDER BY p.rate DESC

    product_rows, err := db.Query(query, "'%" + name + "%'")
    

    I got my soltion from this thread

    0 讨论(0)
  • 2020-12-14 19:48

    You need to put the like pattern in single quotes:

    SELECT p.id, p.name, p.description, p.price, p.image, p.rate
    FROM products AS p
    WHERE LOWER(p.name) LIKE '%' || $1 || '%'
    ORDER BY p.rate DESC;
    
    0 讨论(0)
提交回复
热议问题