Frage

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;

An included QtSql to my main file.

When I run this code I get the error:

QSqlQuery::prepare: database not open

Any ideas will me much appreciated.

P.S.: I use c++ on Linux Ubuntu 12.04 and used LibreOffice Base to create my database.

War es hilfreich?

Lösung

After a bit of google-ing - openoffice libre's internal database is using HSQLDB (natural choice for Java). Here's a small discussion about HSQLDB.

It appears that some versions of openlibre base is also able to connect to external databases. I would recommend setting up something that is more accessible to C++, specifically Qt.

Only a few drivers like ODBC & SQLite is included by default.

Which means that depending on the database being used, one may need to get additional source code (or packages) and compile a plugin/dll/so. The library is loaded dynamically (i.e. run-time) by the QtSql module. I've run into this for mysql drivers.

When you get all of that setup, your call to addDatabase should match the kind of database you're using.

QSqlDatabase::addDatabase( "QODBC" );  // For something like MSSQL
QSqlDatabase::addDatabase( "QSQLITE" );  // For SQLite
QSqlDatabase::addDatabase( "QMYSQL" );  // For MySQL

Personally, if you're just doing this for kicks, a quick and easy database is SQLITE. You can even download plugins/extensions for Mozilla Firefox that will offer you a GUI to the database.

Andere Tipps

Driver not loaded

you need the QSQLITE driver.

db.drivers() returns a list of all the available database drivers.

In Ubuntu 12.04 the driver for sqlite is in a package named libqt4-sql-sqlite.

But: is odb a sqlite database??

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName( "Xmato.odb" );
if (db.open())
{
    QSqlQuery query(db); // if multiple connections used, without the `db` in constructor    will cause the query to use the default database (first opened and available one)
    query.exec("select * from members");
}

should do the same. username and password are not needed and since it is a file, you just have to use setDatabaseName to set what file you want to open.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top