Problem with SQLite & Qt - c++

This is the code which has problem:
QMessageBox::information(this, "Connexion Open", "Connexion BD Ok!");
QSqlQuery req;
req.exec("SELECT * FROM reservation");
while(req.next()) {
float id = req.value(0).toFloat();
text2->setText(" "+QString::number(id)+" " );
The message "Connexion BD Ok!" appears perfectly.
How can I retrieve the result of the DB knowing that the DBMS(SGBD) is SQLite?
Thank You

It looks like you are already retrieving the id, so I'm guessing that your question is how you connect to a sqlite database in the first place with Qt. You typically specify the database when you are connecting. Something like:
QSqlDatabase db = QSqlDatabase::addDatabase(ntr("QSQLITE"));
QFileInfo dbPath(pathToDb, dbFileName);
db.setDatabaseName(dbPath.absoluteFilePath());
if (!db.open()) {
qDebug() << ntr("Could not open database:") << db.databaseName();
}
if (db.isOpenError()) {
QSqlError err = db.lastError();
qDebug() << ntr("Last error:") << err.text();
}

Related

Connecting to Azure SQL Server with Qt on Linux

I am trying to connect to a Azure SQL Server database with Qt on Linux but I have not could make it. I tried some like this: Connection to SQL Server with qt but the connection is never opened.
My code is so simple:
QString connectionTemplate = "DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;";
QString connectionString = connectionTemplate.arg("tcp:my-database.database.windows.net,1433").arg("my-database");
for(int i = 0; i < QSqlDatabase::drivers().size(); i++) {
qDebug() << QSqlDatabase::drivers().at(i);
}
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName(connectionString);
db.setUserName("user#my-database");
db.setPassword("My password");
//db.setConnectOptions("Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;");
bool ok = false;
try {
ok = db.open();
} catch(QException ex) {
qDebug() << ex.what();
}
qDebug("%s=%d", "conexión abierta", ok);
QSqlQueryModel *model = new QSqlQueryModel;
QString query = "SELECT 1 AS test_col";
model->setQuery(query, db);
db.close();
I already have the QODB and QODBC3 drivers so I don't know why I am unable to make the connection.
Is some related to driver, Qt, Azure or similar?
This is what I am doing and it works perfect for me:
Note: connName is the connection name on which I am opening the database.
QString connectionString = "Driver={ODBC Driver 13 for SQL Server};"
"Server=tcp:xxx.database.windows.net,1433;"
"Database=ABC;"
"Uid=aaa#xxx;"
"Pwd=***;"
"Encrypt=yes;"
"TrustServerCertificate=no;"
"Connection Timeout=30;";
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", connName);
db.setDatabaseName(connectionString);
if (db.open())
{
return true;
}
else
{
QString error = db.lastError().text();
return false;
}

SQLite CREATE query in QT

dataBase = QSqlDatabase::addDatabase("QSQLITE");
dataBase.setDatabaseName("login_password.sqlite");
QSqlQuery authQuery;
if(!dataBase.open())
{
qDebug() << dataBase.lastError().text();
}
QString create("CREATE TABLE BASE(LOGIN VARCHAR(15) PRIMARY KEY NOT NULL, "
"PASSWRD TEXT(50) NOT NULL, RIGHTS INT NOT NULL);");
bool state = authQuery.exec(create);
if(!state) qDebug() << "Не удалось создать таблицу!";
What's wrong with query and is it possible to make text PRIMARY KEY?
From the docs:
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.
In your question, you are creating the QSqlQuery before opening the database, you have to move the authQuery declaration statement after the dataBase.open() call, like this:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("login_password.sqlite");
if (!db.open())
qDebug() << "error opening database: " << dataBase.lastError().text();
QSqlQuery authQuery;
QString create("CREATE TABLE BASE(LOGIN VARCHAR(15) PRIMARY KEY NOT NULL, "
"PASSWRD TEXT(50) NOT NULL, RIGHTS INT NOT NULL);");
if(!authQuery.exec(create)){
qDebug() << "error executing statement: " << authQuery.lastError().databaseText();
}

How to connect client server system with SQlite

In client server program I want the message received from client save in "SQLite" database.I mean as code below shows "IPAddress, message and date" from server save in database.How should i connect these together? Thanks in advance.
QString IPAddress= m_client->peerAddress().toString();
qDebug()<<"IP Address:"<< IPAddress;
}
void myserver::readSocket()
{
QByteArray message = m_client->readAll();
qDebug() <<" Data in: " << message;
QDate date=QDate::currentDate() ;
qDebug() << date;
m_client->write(message);
}
void MainWindow::createdata()
{
QSqlQuery query;
query.exec("DROP TABLE messages");
query.exec("CREATE TABLE messages("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"IPAddress VARCHAR(20),"
"date VARCHAR(10),"
"message VARCHAR(30))");
query.prepare("INSERT INTO messages(IPAddress, date, message) values(?,?,?)");

Copy tables between sqlite databases, qt, causes error

I want to write the contents of my SQlite database on user click to another SQlite database. For this I am trying to make connections to two databases and do select query from one db and in transaction do insert query to another. But I gets error on connection creation itself.
In header file:
private:
QSqlDatabase database;
QSqlDatabase mHistoryDB;
In source file:
qDebug() << Q_FUNC_INFO << "Invoked";
database = QSqlDatabase::addDatabase("QSQLITE");
mHistoryDB = QSqlDatabase::addDatabase("QSQLITE");
#ifdef Q_OS_WIN
database.setDatabaseName("C:/ANDROID_DATABASE/RestPos.sqlite");
mHistoryDB.setDatabaseName("C:/ANDROID_DATABASE/History/RestPos.sqlite");
#else
database.setDatabaseName("/mnt/sdcard/pos/RestPos.sqlite");
mHistoryDB.setDatabaseName("/mnt/sdcard/pos/History/RestPos.sqlite");
#endif
While running I gets the following error:
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
If I use only database connection there occurs no error. I am not sure how to do copy with single connection.
My current copy code is as below:
bool readStatus = false,
writeStatus = false;
if (database.isOpen() && mHistoryDB.open())
{
QSqlQuery readQuery (database);
QSqlQuery writeQuery(mHistoryDB);
readStatus
= readQuery.exec("SELECT costcentre_id, bill_no, bill_date "
"FROM BillHdr");
qDebug() << Q_FUNC_INFO << getLastExecutedQuery(readQuery);
if (readStatus)
{
mHistoryDB.transaction();
writeQuery.prepare("INSERT INTO BillHdr "
"(costcentre_id, bill_no, bill_date) "
"VALUES (:costcentre_id, :bill_no, :bill_date)");
while(readQuery.next())
{
if (readQuery.isValid())
{
BillHeader billHdr;
billHdr.costCenterId = readQuery.value(0).toString();
billHdr.billNumber = readQuery.value(1).toDouble();
billHdr.date = readQuery.value(2).toDate();
writeQuery.bindValue(":costcentre_id", billHdr.costCenterId);
writeQuery.bindValue(":bill_no", billHdr.billNumber);
writeQuery.bindValue(":bill_date", billHdr.date);
writeStatus = writeQuery.exec();
qDebug() << Q_FUNC_INFO << getLastExecutedQuery(writeQuery);
if (!writeStatus)
{
qDebug() << Q_FUNC_INFO << "error in write" <<
writeQuery.lastError().text();
mHistoryDB.rollback();
mHistoryDB.close();
break;
}
}
}
writeStatus = mHistoryDB.commit();
qDebug() << Q_FUNC_INFO << "commit:" << writeStatus;
if (!writeStatus)
{
mHistoryDB.rollback();
}
mHistoryDB.close();
}
}
qDebug() << Q_FUNC_INFO << "Exits" << writeStatus;
return writeStatus;
We can read from the Qt documentation about QSqlDatabase :
Warning: If you add a connection with the same name as an existing connection, the new connection replaces the old one. If you call this
function more than once without specifying connectionName, the default
connection will be the one replaced.
So when you add a database multiple times within a specific name or without specifying any (default connection), the connection is replaced and that warning appears.
you should call QSqlDatabase::addDatabase() once for each of the databases with different connection names :
database = QSqlDatabase::addDatabase("QSQLITE", "database_Connection");
mHistoryDB = QSqlDatabase::addDatabase("QSQLITE", "mHistoryDB_Connection");

SQLITE out of memory Unable to execute statement

I tried using sqlite in qt but I’ve come across an error.
qDebug() << QSqlDatabase::drivers();
QSqlDatabase DB = QSqlDatabase::addDatabase("QSQLITE");
DB.setDatabaseName("/Volumes/MAJID/majid/Naminic/db0.db");
QSqlQuery createQuery;
qDebug()<< "open: " << DB.open();
createQuery.exec("CREATE TABLE contact(name,tell)");
qDebug() << createQuery.lastError().text();
qDebug() << "insert : " << createQuery.exec("insert into contact(name,tell) values('a','b')");
qDebug() << createQuery.lastError().text();
and this is the out put of the debug :
(“QSQLITE”, “QODBC3”, “QODBC”)
open: true
out of memory Unable to execute statement
insert : false
out of memory Unable to execute statement
A couple problems I see that should get this working.
1. You need to pass the database object to the QSqlQuery when you create it.
The below line is wrong
QSqlQuery createQuery;
Change it to the following and you should be good
QSqlQuery createQuery(DB);
2. You need to open the database before you create the QSqlQuery object. The connection to the database needs to be open if you initialize the QSqlQuery object with it. So instead of this:
QSqlQuery createQuery(DB);
qDebug()<< "open: " << DB.open();
do this
qDebug()<< "open: " << DB.open();
QSqlQuery createQuery(DB);
That should get things working.
open database before set the query(db) works for me.
add this to the head.
if(!db.isOpened()) db.open();
if(db.isOpenError()) return false;