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
WHERE LOWER(p.name) LIKE %$1% ORDER BY p.rate DESC
If I exec this query directly in PostgreSQL it work but in Golang says:
pq: syntax error at or near "%"
How can I fix it? I tried with "\%" but didn't works. thanks.
here is the complete source code
func FindByName(name *string) ([]*Product, error) {
db, err := db.StablishConnection()
if err != nil {
log.Fatal(err)
panic(err)
}
defer db.Close()
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)
if err != nil {
return nil, err
}
if product_rows == nil {
return nil, errors.New("No Products Named " + *name)
}
products := []*Product{}
for product_rows.Next() {
product := new(Product)
err = product_rows.Scan(&product.Id,
&product.Name,
&product.Description,
&product.Price,
&product.Image,
&product.Rate)
if err != nil {
panic(err)
}
products = append(products, product)
}
return products, nil
}
The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. The percent sign represents zero, one, or multiple numbers or characters.
You construct a pattern by combining literal values with wildcard characters and use the LIKE or NOT LIKE operator to find the matches. PostgreSQL provides you with two wildcards: Percent sign ( % ) matches any sequence of zero or more characters. Underscore sign ( _ ) matches any single character.
LIKE and ILIKE allow pattern matching within character-based column data. Their syntax is identical, but LIKE is case-sensitive, while ILIKE is case-insensitive.
Install Go and pq connector Change directory into the project folder, such as cd %USERPROFILE%\go\src\postgresqlgo . Set the environment variable for GOPATH to point to the source code directory. set GOPATH=%USERPROFILE%\go . Install the Pure Go Postgres driver (pq) by running the go get github.com/lib/pq command.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With