简体   繁体   中英

Can't get delphi SQL LIKE to work with %

I'm doing a school project and need to code a query to filter a dataset to certain variables. All my SQL works fine, except I can't get the LIKE statement to work with %-signs. I believe my syntax is wrong. Can anybody please tell me what I'm doing wrong. Thanks

The code:

qryMovie.SQL.Clear;
qryMovie.SQL.Add('SELECT * FROM Movies');
qryMovie.SQL.Add('WHERE Genre =  ' + QuotedStr(genre));
qryMovie.SQL.Add('AND Price BETWEEN ' + minPrice + ' AND ' + maxPrice);
qryMovie.SQL.Add('AND Title LIKE %' + title + '%');
qryMovie.Open;

Error produced:

'Syntax error in query expression 'Genre = 'Action/Adventure' AND Price BETWEEN 0 AND 200 AND Title LIKE %Star Wars%''

LIKE %Star Wars%

but you need

LIKE '%Star Wars%'

You need to quote % with ' :

qryMovie.SQL.Add(' AND Title LIKE ''%' + title + '%''');

Anyway you should use binded parameters instead of concatenating SQL string. It is error-prone and could lead to SQL Injection attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM