由于 ' (单引号)是SQL的标准字符符号,所以在SQL语句中间遇到 ' 时要做特殊处理。
1. 使用 QuotedStr 函数
QuotedStr的作用是使字符串包含单引号:
在字符的前后加上( ')号,因为在DELPHI中字符赋值是需要引号的
比如
CommandText := CommandText + QuotedStr(Edit1.Text);
Sql := 'select ... from ... where uName=' + QuotedStr(Edit1.Text);
上面的语句还可以写成:
Sql := 'select ... from ... where uName=' + Char(39) + stringreplace(Edit1.Text,'''','''''',[rfReplaceAll])+ Char(39);
Char(39) 代码一个分号 stringreplace 把字符串中的单引号换成两个单引号,只是还是QuotedStr好用,前后加了单引号而且把见到的单引号都替换成两个单引号了;
2、采用替代法 即用 " 代替 ' ,正好delphi有现在的函数,
例如:
UName :=stringreplace(ComBoUser.Text,'''','''''',[rfReplaceAll]);
UPwd :=StringReplace(EPassword.Text ,'''','''''',[rfReplaceAll]);
Sql :='select UAuth from VUser where UName=''' +UName +''' and UPwd=''' +UPwd +'''';
adoquery1.SQL.Add(Sql);
3、采用参数法 即用参数代替变量 ,此时不需要对变量做任何处理,例如:
AdoQuery1.SQL.Add('update GoodsReason set GRCode =:VC,GRName =:VN where GID =:ID');
AdoQuery1.Parameters.Clear;
AdoQuery1.Parameters.CreateParameter('VC',ftString,pdinput,10,EGCode.Text );
AdoQuery1.Parameters.CreateParameter('VN',ftString,pdinput,20,EGName.Text );
AdoQuery1.Parameters.CreateParameter('ID',ftInteger,pdinput,8,StrToInt(GoodsId.Caption));
AdoQuery1.ExecSQL ;