[SOLVED] QtSql connection
-
I am trying to create a connection to a database and insert/delete/make queries to the database. I know SQL relatively well but I cannot seem to wrap my head around it in Qt. I used to program in Delphi.
This is my code so far:
@QSqlDatabase db;
db.addDatabase("QSQLITE");
db.setHostName( "localhost" ); //I don't know if i should include this the database is in the same directory as my program
db.setDatabaseName( "Xmato.odb" );
db.setUserName( "" ); //There is no username
db.setPassword( "" ); //There is no password
db.open();
db.prepare("SELECT * FROM Members");
db.exec();
@
I have added this to my .pro file:@QT += sql;@
And added this to my main file:
@#include <QtSql>@
When I run this code I get the error:
@QSqlQuery::prepare: database not open@
db.lastError().text() returns:
@Driver not loaded@
Which driver sould I use and what are the drivers?
Any ideas will me much appreciated.
P.S.: I use c++ on Linux Ubuntu 12.04 and use Qt Creator and used LibreOffice Base to create my database.
-
Okay, I found the solution...
- I uninstalled Qt
- Downloaded the tarball (.tar.gz file containing the source code for Qt (Windows users use the .zip file)).
- Configure with this command:
@
./configure -plugin-sql-sqlite
@
or
@
./configure -qt-sql-sqlite
@If it gives you some shit about qtwebkits use just add the following to the configure command:
@
-skip qtwebkit
@- make and install with this commands:
@
make
@
after a few frieking hours, then
@
sudo make install
@- Now this is very important:
when you declare QSqlQuery, declare it after you added the driver, i.e.:
@
QSqlDatabase db;
db = QSqlDatabase::addDatabase( "QSQLITE" );
if( db.open() )
{
QSqlQuery query; //NOTE THIS IS AFTER THE addDatabase("QSQLITE") FUNCTION!
}
@
If for some reason you need the query to be declared earlier (like in a class) do this:
@
QSqlDatabase db;
QSqlQuery query;//This is in another part of the code
db = QSqlDatabase::addDatabase( "QSQLITE" );
if( db.open() )
{
QSqlQuery tmp;
query = tmp;
}
@