[solved]QSQLITE
-
I had the same problem as many people with "QMYSQL driver not loaded" and I couldn't solve it. Instead of MySQL i decided to use SQLite, because it seems have been working. SQLite folder is on my desktop, there I have database logs_database. I added QT += sql into .pro file. And wrote some code:
#include <QCoreApplication>
#include <QtSql>
#include <QtCore>int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("logs_database");
// I tried to use such way: moved SQLite folder into debug folder and wrote this:
// QString pathToDB = QDir::currentPath()+QString("\SQLite\logs_database");
// db.setDatabaseName(pathToDB);if(db.open()) { qDebug() << "Opened!"; QSqlQuery query; query.exec("insert into people (Name, id) values ('Michael', 5)"); } else { qDebug() << "Error: " << db.lastError(); } return a.exec();
}
Every time it says to me Opened! But command "insert into people (Name, id) values ('Michael', 5)" has no effect
-
Do you see the insert in the database? (exec() returns boolean to let you know if it was successfully executed) It doesn't return the record of what was inserted. What effect were you expecting?
You could do
#include <QDebug> ... // add after the insert exec(); QSqlQuery query("SELECT Name, id FROM people"); while(query.next()) { // where value(0) and value(1) represents name, id columns respectively qDebug() << "name: " << query.value(0).toString(); qDebug() << "id: " << query.value(1).toString(); }
I hope this helps you.
-
@mrdebug
It says: no such table. I'm sure it's because program doesn't work with my database, actually I don't know which database it uses because I can putt some trash like aiefhah instead logs_database and it still says Opened! -
@David.G
If I understood you correctly, I expected that after compilation of this program I will open sqlite, then write select * from people and I will see a new values in this table, but there is no change. I guess it's because of that error: no such table: people Unable to execute statement -
Thaks everyone and sorry for stupid questions, it was my mistake. I just put the database file into debug folder and now everything works fine=)
-
@AntonZelenin Ah, alright I think I understand now, my bad if I misunderstood you.
- When the application starts, did you create the schema? The database will indeed open, or rather create a new one in the case of QSLITE if it doesn't exists, but it will be empty. Thus:
- If you already have a working database then you would need to point the path there, however, if you have the schema (SQL file with
CREATE TABLE IF NOT EXISTS
etc) you can execute at the start of the application before it starts all the transactions.