Cemetery_Gates
Cemetery_Gates

Reputation: 67

How to use variables in a QSqlQuery?

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?

Upvotes: 3

Views: 1276

Answers (2)

scopchanov
scopchanov

Reputation: 8399

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();

Upvotes: 2

Minh
Minh

Reputation: 1725

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

Upvotes: 1

Related Questions