3

I want to implement a method that will check search for entries that have the localhost ip address upon exiting the program and delete those rows.

The problem is, I'm not sure how to do this in Qt I can't really find anything specific when I search. Is there a way to create a sql variable in qt, or can I use a qt variable in an sql query? To give you an idea of what I want to do please see below:

   QSqlQuery query;
   query.exec("DELETE FROM host WHERE ip = <localhost_variable??>");

Any tips?

2
  • I can't really find anything specific when I search Did you read the documentation of QSqlQuery? Commented Nov 5, 2020 at 9:50
  • Did the solution work for you? Commented Nov 17, 2020 at 0:30

2 Answers 2

2

Solution

You might of course inject the value directly in the query, as @NgocMinhNguyen suggested, but this is a not recommended, as it opens a security hole.

The recommended way to achieve this, is using query bindings.

Example

Here is a short example I have prepared for you to demonstrate how the proposed solution could be implemented in your case:

QSqlQuery query;

query.prepare("DELETE FROM host WHERE ip = :localhost");
query.bindValue(":localhost", localhost_variable);
query.exec();
Sign up to request clarification or add additional context in comments.

2 Comments

Can you elaborate on what the security hole is and how query binding address that security hole?
@NgocMinhNguyen, From Wikipedia: Prepared statements are resilient against SQL injection because values which are transmitted later using a different protocol are not compiled like the statement template. If the statement template is not derived from external input, SQL injection cannot occur.
1

QSqlQuery::exec() takes a string as a parameter, so you can use:

QSqlQuery query;
query.exec(QString{"DELETE FROM host WHERE ip = %1"}.arg("some_localhost_ip"));

The final query will be:

DELETE FROM host WHERE ip = some_localhost_ip

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.