PDA

View Full Version : How to use QSqlDriver::sqlStatement to create "WHERE column<>value" ?



jezz
14th January 2012, 16:19
I've learned that QSqlDriver::sqlStatement(QSqlDriver::WhereStatemen t, "table1", whereValues, false) can generate a QString like "WHERE column=value", but how do I generate "WHERE column<>value"?

Thanks.

wysota
14th January 2012, 20:23
What exactly are you trying to do? You shouldn't need to interact with QSqlDriver directly.

jezz
15th January 2012, 00:59
Thanks, but I am not using QSqlDriver directly. For example, the following code generate: SELECT "name" from Users WHERE "age" = 20
:

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QSqlRecord rec;
QSqlRecord whereValues;

db.setHostName("localhost");
db.setDatabaseName("D:\\test.db");

bool ok = db.open();

QSqlField f1 = QSqlField("name", QVariant::String);
rec.append(f1);

QSqlField f2 = QSqlField("age", QVariant::Int);
f2.setValue(20);
whereValues.append(f2);

QString stmt = db.driver()->sqlStatement(QSqlDriver::SelectStatement, "Users", rec, false);
QString where = db.driver()->sqlStatement(QSqlDriver::WhereStatement, "Users", whereValues, false);

stmt.append(QLatin1Char(' ')).append(where);


But how to generate the following:

SELECT "name" from Users WHERE "age" <> 20
SELECT "name" from Users WHERE "age" > 20


I am trying to create application that can change database system such as between SQLite, PostgreSql etc, without hardcoding the SQL statements.

wysota
15th January 2012, 01:25
Thanks, but I am not using QSqlDriver directly.
No? So what's that?

db.driver()



But how to generate the following:

SELECT "name" from Users WHERE "age" <> 20


QSqlQuery q;
q.prepare("SELECT name FROM Users WHERE age <> :val");
q.bindValue(":val", 20);
q.exec();



SELECT "name" from Users WHERE "age" > 20


QSqlQuery q;
q.prepare("SELECT name FROM Users WHERE age > :val");
q.bindValue(":val", 20);
q.exec();



I am trying to create application that can change database system such as between SQLite, PostgreSql etc, without hardcoding the SQL statements.
All databases must respect ANSI SQL so if you constrain yourself to that, all will be fine. It's not possible to build any generic query using the interface you were trying with. That's meant for something else.

jezz
15th January 2012, 01:36
Thanks, but is this considered using QSqlDriver directly? It is in this case actually QSQLiteDriver which is derived from QSqlDriver.

db.driver()

wysota
15th January 2012, 01:44
Yes, it's considered using QSqlDriver directly (as opposed to using QSqlDatabase and QSqlQuery that call QSqlDriver API behind the scenes).