To improve security and prevent SQL injection when operating databases in QT, you can use named placeholders and location placeholders.
This document uses the name placeholder as an example to demonstrate how to bind a value to a placeholder in the like clause. The Code is as follows:
/* Query the maximum number of limitcnt persons in the person table by employee ID. You can use the ***** No: employee ID to be queried ** rslt: query Result ** limitcnt: Maximum number of returned results *** return value: true if successful; otherwise, false is returned. when false is returned, rslt is unavailable. * *** Note: If no matching record is found, the query is successful. */bool selpersonavailable (const qstring & No, qvector <qstring> & rslt, const int limitcnt) {static const qstring funcerrmsg = "query the maximum number of limitcnt persons from the person table by employee ID, % 1 failed to be used on the \ "recognize new card number \" interface. "; qstring SQL =" select PNAM, PNO, rno from person where PNO like: PNO and State <> 'D' limit: limitcnt "; // note, like's percent sign (%) is not directly written to the SQL string bool OK; // _ log (qstring ("NO = % 1, limitcnt = % 2 "). arg (NO ). arg (limitcnt); qsqldatabase DB = qsqldatabase: Database (db_conn_name); qsqlquery query (db); query. prepare (SQL); query. bindvalue (": PNO", qstring ("% 1% "). arg (NO); // Add a percent sign (%) query. bindvalue (": limitcnt", limitcnt1_if(query.exe C () {While (query. next () {rslt. append (query. value (0 ). tostring (); rslt. append (query. value (1 ). tostring (); rslt. append (query. value (2 ). tostring ();} // _ log (qstring ("rslt. size () = % 1 "). arg (rslt. size (); Return true;} else {_ log (query. lasterror (). text (); _ log (funcerrmsg. arg ("query.exe C ()");} return false ;}
Note: The percent sign (%) used in the like clause does not appear in the SQL string, but appears when the placeholder value is bound, in addition, the like clause cannot use single quotation marks (') in SQL strings. Because the placeholder type is a string, you do not need to use single quotation marks (') IN THE like clause ~
If the placeholder position is used, replace: PNO,: limitcnt ?, Then, when bindvalue:
Query. bindvalue (0, qstring ("% 1%"). Arg (NO); // Add a percent sign (%) query. bindvalue (1, limitcnt );
Instead of using a placeholder name, it uses a serial number. Based on the position where the placeholder appears in the SQL string, it ranges from left to right and is 0, 1, 2, 3, 4, 5, 6 ,......
Also, my database uses SQLite.