您现在的位置:首页 >> 基础算法 >> window基础 >> 内容

Delphi中关于如何拼接SQL语句

时间:2011/9/3 15:32:47 点击:

  核心提示:稍微好一点的方法是,使用QuotedStr函数,这个函数用于输出一个单引号括着的字符串。我相信写“'Insert into table(a,b,c) values(' + QuotedStr('ET'...
稍微好一点的方法是,使用QuotedStr函数,这个函数用于输出一个单引号括着的字符串。我相信写“'Insert into table(a,b,c) values(' + QuotedStr('ET') + ',' + QuotedStr('OTL') + ',' + QuotedStr('ORZ') + ')'”,总比你写“'Insert into table(a,b) values(' + ''''ET'''' + ',' + ''''OTL'''' + ',' + ''''ORZ'''' + ')'”可读性要强些吧,这么多引号看着都烦,别说写了。    更好的方法是使用Format函数。此函数一定要多多善用,通过格式化字符串的办法,可大大提高语句的可读性;而且格式化控制符有数字型也有字符串型,免除了你一会IntToStr,一会又StrToInt的痛苦。以上SQL的等效写法是“Format('Insert into table(a,b,c) values(%s,%s,%s)', [QuoteStr('ET'), QuotedStr('OTL'), QuotedStr('ORZ')])”。    本文到此还没结束,大家是否觉得尽管Format能大大提高了语句的可读性,但是写带单引号的字符串时,仍然比较麻烦呢?no problem,其实我们稍稍"扩充"下Format语句就行了:    function FormatSQL(const AFormat: string; const Args: array of const): string;  begin    result := Format(StringReplace(AFormat, '%q', QuotedStr('%s'), [rfReplaceAll, rfIgnoreCase]), Args);  end;    以上SQL的等效写法为“FormatSQL('Insert into table(a,b,c) values(%q,%q,%q)', ['ET', 'OTL', 'ORZ'])”。应该算是比较方便了,我觉得。    此外,参量SQL也是一种可以考虑的方法(不过依旧觉得上述最后一种方法,在解决单引号字符串的问题上,会比较方便点)。

作者:网络 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号