普通网友 2016-06-02 21:49
浏览 42
已采纳

Golang中的Postgres查询出了什么问题(喜欢匹配)

I've seen a very similar problem here, but I'm not certain what the pipes do in the command, and it didn't work for me anyway.

So, here's the code I've tried.

rows, err := db.Query(fmt.Sprintf("SELECT * FROM mytable WHERE mycolumn LIKE 'camel.%'"))

And even though, I have no idea what it's for, I also tried with the pipes.

rows, err := db.Query(fmt.Sprintf("SELECT * FROM mytable WHERE mycolumn LIKE 'camel. || %'"))

So, what it should be doing, is matching anything in that column that starts with camel., so camel.*

The error I'm getting for both examples is

pq: syntax error at or near "("

So i'm guessing for some reason it's passing in more of that line as the command than I would like....maybe a quote problem? I've tried a few other things, but nothing has worked. Any help is appreciated.

  • 写回答

3条回答 默认 最新

  • doujiao1948 2016-06-02 22:01
    关注

    func Sprintf(format string, a ...interface{}) string

    Sprintf formats according to a format specifier and returns the resulting string.

    mt.Println(fmt.Sprintf("SELECT * FROM mytable WHERE mycolumn LIKE 'camel%'"))
    
    //Output:
    //SELECT * FROM mytable WHERE mycolumn LIKE 'camel%!'(MISSING)
    //Ofc postgres will complain
    

    You do not need fmt.Sprintf in this case.

    rows, err := db.Query("SELECT * FROM mytable WHERE mycolumn LIKE 'camel.%'")
    

    works fine.

    But if you really need to use fmt.Sprintf you must escape '%' with '%%'

    rows, err := db.Query(fmt.Sprintf("SELECT * FROM mytable WHERE mycolumn LIKE 'camel.%%'"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看