In Delphi 7, how do I escape a percent sign (%) in the Format function?

自闭症网瘾萝莉.ら 提交于 2019-12-22 02:51:48

问题


I want to do something like this:

SQL.Text := Format('select foo from bar where baz like ''%s%''',[SearchTerm]);

But Format doesn't like that last '%', of course. So how can I escape it? \%? %%?

Or do I have to do this:

SQL.Text := Format('select foo from bar where baz like ''%s''',[SearchTerm+'%']);

?


回答1:


Use another % in the format string:

SQL.Text := Format('select foo from bar where baz like ''%s%%''',[SearchTerm]);



回答2:


%% , IIRC.




回答3:


Obligatory: http://xkcd.com/327/ :-)

Depending on context, your approach might be vulnerable to SQL injection. If the search term comes from user input it would probably be better to use a parameterized query or at least try to sanitize the input.




回答4:


Add 2 percent sign to have 1 single %
Example :

 Format('select foo from bar where baz like ''%%%s%%'',[SearchString])

Gives you

select foo from bar where baz like '%SearchString%'


来源:https://stackoverflow.com/questions/267487/in-delphi-7-how-do-i-escape-a-percent-sign-in-the-format-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!