Pregunta

I have the following problem.

When I use a SQL Select statement to filter records it either gives an error or does not show the record it should.

If the field has a ' in the value it gives an sql error, If the value is (i'm) the error says the sintax is not correct for (i'), so the single ' cuts off the rest of the sql statement,

I have tried using code to change all the ' into " and then i do not get an error, but i do not get any records either.

Below is the code:

To convert the ' into ":

Function RestoreFromsqlFormat(SQLText:String):String;
Var
Sqlnew,sqlold:String;
Begin
   sqlold:=SqlText;
 if Pos('"',SQLText)<>0 then
  Begin
   while Pos('"',sqlold)<>0 do
    Begin
     SqlNew:=Copy(SqlOld,0,Pos('"',SqlOld)-1)+'''';
     SqlOld:=Copy(SqlOld,Pos('"',sqlOld)+1,Length(sqlOld));
    End;
  End;
  Result:=SQlNew+SqlOld;
End;

And when calling the sql select from statement, I am getting the following error :

Active:=False;
   Sql.Text:='select*from backup_folders where (user_id='''+userID+''') and (folder='''+PreparesqlFormat('my name wouldn''t be here')+''')';
   Active:=True;

May i know how to overcome this error ?

¿Fue útil?

Solución

This is the wrong way to use SQL.

Get rid of your PreparesqlFormat() function and use AnsiQuotedStr() instead:

Active := False;
Sql.Text := 'select * from backup_folders where (user_id=' + AnsiQuotedStr(userID, #39) + ') and (folder=' + AnsiQuotedStr('my name wouldn''t be here', #39) + ')';
Active := True;

A better option is to use a parameterized query instead. Let the DB handle quotes for you:

Active := False;
// depending on which DB component you are using, you might need to use @ instead of :
Sql.Text := 'select * from backup_folders where (user_id=:PUserID) and (folder=:PFolder)';
ParamByName('PUserID').AsString := userID;
ParamByName('PFolder').AsString := 'my name wouldn''t be here';
Active := True;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top