What is the problem in QSqlQuery?
-
class QueryBuilder { public: QueryBuilder(); QSqlQuery insert(const QString &query) { QSqlQuery qry; qry.prepare(query); return qry; } }
#include "querybuilder.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QueryBuilder b; b.insert("bla bla ..."); // ---> Output : QSqlQuery::prepare: database not open return a.exec(); }
can you help ?
-
hi
Well, it wants a database open first :)
You seems not to have any?http://stackoverflow.com/questions/7669987/what-is-the-correct-way-of-qsqldatabase-qsqlquery
-
@_compiler
as the Qt docs for QSqlQuery class say:Warning: You must load the SQL driver and open the connection before a QSqlQuery is created. Also, the connection must remain open while the query exists; otherwise, the behavior of QSqlQuery is undefined.
-
@_compiler said:
Well your class can , but when you do- qry.prepare(query);
it wants to talk to DB to check stuff.
-
real class ...
class QueryBuilder { public: QueryBuilder(); QSqlQuery insert(const QString &tableName, QMap<QString,QVariant>/*name,value*/ &values) { QSqlQuery qry; QString str = "INSERT INTO " + tableName +" ("; QString val = "VALUES("; QMapIterator<QString, QVariant> it(values); while (it.hasNext()) { it.next(); str += it.key(); val += ":" + it.key(); if(it.hasNext()) { str += ", "; val += ", "; }else { str += ") "; val += ") "; } } str += val; qry.prepare(str); ///... return qry; } }
-
@_compiler
ok, but prepare need open database. -
well just wait until later to call qry.prepare(str); ?
The rest of the code just create the string.but please notice what @raven-worx says. !
So maybe you should rethink the design of QueryBuilder to not use
QSqlQuery before a database is created and open.what is the role of QueryBuilder ?
-
@mrjj QueryBuilder class set of query.
for example ;
QueryBuilder b; QSqlQuery q1, q2, q3, q4; q1 = b.insert("bla bla ..."); q2 = b.update("bla bla ..."); q3 = b.remove("bla bla ..."); q4 = b.select("bla bla ..."); SqlWorkerThread *thread = new SqlWorkerThread(0); //signal slot definitions .... thread.addQuery(q1); thread.addQuery(q2); thread.addQuery(q3); thread.addQuery(q4); thread.start();
-
Ok, i see, its a helper class.
Well you need to open a db then.
You dont need to do it in QueryBuilder.
If you open a db in main , QSqlQuery
will use this DB. You dont need pointer or reference.
Its handled internally.