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

格式化包含'%'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>
  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件