dsue14118
2018-11-27 14:05
浏览 217
已采纳

格式化包含'%'golang的字符串[重复]

This question already has an answer here:

I have an SQL query that looks like this:

SELECT name FROM sessions WHERE name ILIKE 'org_name.%';

but I'm actually interested in replacing 'org_name' with format string (%s).
I was trying to do something like this:

query := fmt.Sprintf("SELECT name FROM sessions WHERE name ILIKE '%s.%'", "org_name2")

but go seems to not like it, since writing %' isn't valid as format string.
I know I can solve it with do it in that way:

orgName := "org_name2"
condition := fmt.Sprintf("%s", orgName) + ".%"
query := fmt.Sprintf("SELECT name FROM sessions WHERE name ILIKE '%s'", condition)


but, I'd rather not, since the variable here is solely the org_name.
Is there a solution for this?
Thanks!

</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案

  • 使用Printf转义变量 1个答案 \ r

    我有一个看起来像这样的SQL查询:

      SELECT 在名称中来自会话的地方,名称类似'org_name。%'; 
       
     
     

    ,但我实际上对将'org_name'替换为格式字符串(%s)感兴趣。 > 我正在尝试执行以下操作:

      query:= fmt.Sprintf(“从会话名中选择名称,而名称像'%s。%'”  ,“ org_name2”)
       
     
     

    ,但是似乎不喜欢它,因为写%'作为格式字符串无效。
    我知道 我可以用它解决 方式:

      orgName:=“ org_name2” 
    condition:= fmt.Sprintf(“%s”,orgName)+“。%” 
    query:= fmt.Sprintf  (“ SELECT FROM FROM where WHERE name ILIKE'%s'”,条件)
       
     
     


    但是,我宁愿不要,因为这里的变量是
    是否有解决方案?
    谢谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douqihua6212 2018-11-27 14:08
    已采纳

    As documented in the fmt package, a literal % can be represented by %% in a printf format string:

    query := fmt.Sprintf("SELECT name FROM sessions WHERE name ILIKE '%s.%%'", orgName)
    

    But be aware, you should NEVER, EVER build your SQL queries this way! You are potentially opening yourself for SQL injection attacks. Instead, you should pass parameterized arguments:

    query := "SELECT name FROM sessions WHERE name ILIKE ?"
    rows, err := db.Query(query, orgName + ".%")
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题