加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 相当于php的mysql_real_escape_string

发布时间:2020-12-15 09:40:06 所属栏目:大数据 来源:网络整理
导读:我需要一些动态SQL来将大量值插入到数据库中. INSERT INTO table1 (a,b,c,d) VALUES (1,2,3,'string with possible quotes'),.... 因为我想每批插入大约1,000行,所以参数实际上不是一个选项. 在php中我会使用mysql_ lib和mysql_real_escape_string来防止错误
我需要一些动态SQL来将大量值插入到数据库中.

INSERT INTO table1 (a,b,c,d) VALUES (1,2,3,'string with possible quotes'),....

因为我想每批插入大约1,000行,所以参数实际上不是一个选项.
在php中我会使用mysql_ lib和mysql_real_escape_string来防止错误和SQL注入.

如何在Delphi中转义字符串值?

解决方法

前段时间我写了一个delphi等效函数,遵循关于 mysql_real_escape_string函数的MySql文档.

The string in from is encoded to an escaped SQL string,taking into
account the current character set of the connection. The result is
placed in to and a terminating null byte is appended. Characters
encoded are “”,“’”,“””,NUL (ASCII 0),“n”,“r”,and Control+Z.
Strictly speaking,MySQL requires only that backslash and the quote
character used to quote the string in the query be escaped.
mysql_real_escape_string() quotes the other characters to make them
easier to read in log files

很明显,这里忽略了考虑当前连接字符集的部分.

function StringReplaceExt(const S : string; OldPattern,NewPattern:  array of string; Flags: TReplaceFlags):string;
var
 i : integer;
begin
   Assert(Length(OldPattern)=(Length(NewPattern)));
   Result:=S;
   for  i:= Low(OldPattern) to High(OldPattern) do
    Result:=StringReplace(Result,OldPattern[i],NewPattern[i],Flags);
end;

function mysql_real_escape_string(const unescaped_string : string ) : string;
begin
  Result:=StringReplaceExt(unescaped_string,['',#39,#34,#0,#10,#13,#26],['',''#39,''#34,'','n','r','Z'],[rfReplaceAll]
  );
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读