Reputation: 751
i'm trying to connect to a sql database with the Qt-Framework.
Unfortunately db.open() always returns true (you can set any password, hostname, etc...), despite no connection is established(?). I derive that from the query not having any effect on the database.
I'm using LAMPP on Ubuntu 14.04.
I've got the following code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QSql>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlQuery>
void MainWindow::on_ButtonSQL_clicked()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "con1");
db.setHostName("localhost");
db.setDatabaseName("kinectshop2015");
db.setUserName("root");
db.setPassword("");
QMessageBox msgBox;
if (db.open()) {
msgBox.setText("Yay! Your database host is "+db.hostName()+" .\n"+" The name of the database is "+db.databaseName()+".");
msgBox.exec();
}
QSqlQuery query;
query.exec("INSERT INTO users (id, username, balance, isAdmin)" "VALUES(3, 'somebody', 10000, 1)");
}
Upvotes: 4
Views: 1691
Reputation: 751
Here is what solved my problem. I used the driver QMYSQL instead of QSQLITE. I had only used the latter, because the first one couldn't be loaded. On Ubuntu & QT5 simply type sudo apt-get install libqt5sql5-mysql to resolve the problem.
Upvotes: 0
Reputation: 2203
One problem is that you are specifying a connectionName.
QSqlDatabase QSqlDatabase::addDatabase(const QString & type, const QString & connectionName = QLatin1String( defaultConnection ))
If connectionName is not specified, the new connection becomes the default connection
Given that your db connection is not the default connection, you need to tell the QSqlQuery which db to use, i.e.
QSqlQuery query(db);
query.exec("INSERT INTO users (id, username, balance, isAdmin)" "VALUES(3, 'somebody', 10000, 1)");
The other 'problem' is that with sqlite you always create a new database by the call you are making, thus the problem is not that the DB is not open but that its contents are not right (since it will be empty if you specify a non existing filename). If I take your code and add
qDebug() << query.lastError();
after the query.exec
it rightfully complains that
QSqlError(1, "Unable to execute statement", "no such table: users")
If I include a statement to create the table before the insert query
QSqlQuery createTable("create table users ( id INTEGER, username TEXT, balance REAL, isAdmin INTEGER)",db);
createTable.exec();
I correctly get the table in the newly create db file and it has the entry that you are trying to insert.
Does this help?
Upvotes: 2