转到postgresql LIKE查询 [英] Go postgresql LIKE query
本文介绍了转到postgresql LIKE查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Go和PostgreSQL(pq驱动程序),我有以下查询
SELECT p.id, p.name,p.description,p.price,p.image,p.rate
FROM产品AS p
WHERE LOWER(p.name)LIKE%$ 1%ORDER BY p.rate DESC
如果我直接在PostgreSQL中执行这个查询,但它在Golang中说:
pq:语法错误处于或接近%
我该如何解决它?我尝试使用\%,但没有奏效。
thanks。
这里是完整的源代码
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产品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
}
如果product_rows == nil {
return nil,errors.New(没有产品命名为+ * name)
}
products:= [] * Product {}
for product_rows .Next(){
product:= new(Product)
err = product_rows.Scan(& product.Id,
& product.Name,
& amp; ampc t.Description,
& product.Price,
& product.Image,
& product.Rate)
if err!= nil {
panic err)
}
产品=追加(产品,产品)
}
退货产品,零
}
解决方案
您需要将像
模式放在单引号中:
SELECT p.id,p.name,p.description,p.price,p.image,p.rate
FROM产品AS p
WHERE LOWER(p.name)LIKE'%'|| $ 1 || '%'
ORDER BY p.rate DESC;
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
}
解决方案
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;
这篇关于转到postgresql LIKE查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文