How to deal: QSqlQuery::exec() returns false - c++

I'm using Qt and sqlite3. The problem is:
QSqlQuery::exec() returns false.
I thought it is caused by QSqlDatabase::open() because it always returns true!
I found that actually does not matter what i set using QSqlDatabase::setDatabaseName(), it will return true, because sqlite will create non existing DB.
I used QFile::exist to test if DB exists. But everything is fine and QFile sees the db.
Code:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("temp_client_db.sl3");
QFile datebase("temp_client_db.sl3");
if (!datebase.exists() || !db.open())
{
QMessageBox::critical(this, "Error", "Database isn't connected.");
}
else
{
QSqlQuery query;
query.prepare("SELECT * FROM exist_ask");
if (!query.exec())
{
QMessageBox::critical(this, "Error", "\"SELECT exist_ask\" works badly.");
}
else
{
...

I just did not add the database to the build directory.

Related

Why QSqlDatabase object won't work if addDatabase method assigned later?

This won't work:
{
QSqlDatabase db;
db.addDatabase("QSQLITE", "manDb");
QString path = QDir::currentPath()+"/"+"Sqlite.db";
db.setDatabaseName(path);
if(db.open())
{
qDebug()<< "Database Created successfully...";
}else{
qDebug()<< "Failed to create Database...";
}
}
QSqlDatabase::removeDatabase("manDb");
Output: Failed to create Database...
But this works:
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "manDb");
QString path = QDir::currentPath()+"/"+"Sqlite.db";
db.setDatabaseName(path);
if(db.open())
{
qDebug()<< "Database Created successfully...";
}else{
qDebug()<< "sucessfully Failed to create Database...";
}
}
QSqlDatabase::removeDatabase("manDb");
Output: Database Created successfully...
Why?
Your first code sample does not work because according to documentation
QSqlDatabase db;
Creates an empty, invalid QSqlDatabase object. Use addDatabase(), removeDatabase(), and database() to get valid QSqlDatabase objects.
Then you try to call static QSqlDatabase::addDatabase method with db.addDatabase("QSQLITE", "manDb"); which returns QSqlDatabase class instance, but you do not assign it's return value to variable to use it later.
Adds a database to the list of database connections using the driver type and the connection name connectionName. If there already exists a database connection called connectionName, that connection is removed.
The database connection is referred to by connectionName. The newly
added database connection is returned.
So, in the first sample you tried to use QSqlDatabase in wrong way. Meanhile your second sample is a correct usage.

I can't insert data into my sqlite3 database using qt 6

I have a test.db database on my project directory, which I'm trying to insert data into. The database is connected, but I can't seem to insert data in it. The query is not executed at all (it seems), since the qDebug shows "Bad".
QSqlDatabase connectDB(){
QSqlDatabase db= QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("test.db");
return db;
}
void planner::on_dataSend_clicked()
{
QSqlDatabase datba = connectDB();
if (datba.open()){
qDebug()<< "DB Suc";
} else{
qDebug() << "DB Fail";
}
QString what = ui->addPlan->text();
QSqlQuery qry;
qry.prepare("insert into plan values :what");
qry.bindValue(":what",what);
if (qry.exec()){
qDebug()<< "Good";
qry.clear();
} else{
qDebug()<<"Bad";
qDebug()<<qry.lastError();
qry.clear();
}
datba.close();
ui->addPlan->clear();
}
I'm using DB Browser for SQLite, and this is the database
The error that QSqlError shows is parameter count mismatch here
On SQLITE table, there is a default column as a primary key called rowid, you need to spécify the column that you want to add like this:
qry.prepare("insert into plan (column_name) values (:what)");

connection 'qt_sql_default_connection' is still in use, all queries will cease to work

I've made separate functions for open and close connection.But it wont let me to add new record on new form.
this is login header file.
public:
QSqlDatabase mydb;
void connClose()
{
//QString connection;
//connection = mydb.connectionName();
mydb.close();
//mydb.removeDatabase(connection);
mydb.removeDatabase(mydb.connectionName());
}
bool connOpen()
{
mydb=QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("./Poem.db");
if(mydb.open())
{
return true;
}
else if(!mydb.open())
{
return false;
}
}
this is the other form add button :
QString Title,Group,Poem;
Title = ui->lineEdit->text();
Group = ui->label_2->text();
Poem = ui->textEdit->toPlainText();
MainWindow mainwindow;
mainwindow.connOpen();
QSqlQuery * qry1 = new QSqlQuery(mainwindow.mydb);
qry1->prepare("insert into Poems(Title,Poem,Group) values ('"+Title+"','"+Poem+"','"+Group+"')");
if(qry1->exec())
{
QMessageBox::critical(this,tr("درج شعر جدید"),tr("شعر اضافه شد"));
mainwindow.connClose();
}
I get this errors :
duplicate connection name 'qt_sql_default_connection', old connection removed.
connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
You are committing exactly what Qt QSqlDatabase Documentation warns about:
Warning: There should be no open queries on the database connection
when this function is called
...
// WRONG
QSqlDatabase db = QSqlDatabase::database("sales");
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
QSqlDatabase::removeDatabase("sales"); // will output a warning
// "db" is now a dangling invalid database connection, // "query"
contains an invalid result set
and the correct is:
{
QSqlDatabase db = QSqlDatabase::database("sales");
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
}
// Both "db" and "query" are destroyed because they are out of scope
QSqlDatabase::removeDatabase("sales"); // correct
So in your case you execute query qry1 and remove the database within same scope (i.e before qry1 goes out of scope), you should modify your code to make sure qry1 is executed and gets destroyed / goes out of scope / before deleting the database. Try this:
{
QSqlQuery * qry1 = new QSqlQuery(mainwindow.mydb);
qry1->prepare("insert into Poems(Title,Poem,Group) values ('"+Title+"','"+Poem+"','"+Group+"')");
if(qry1->exec())
{
QMessageBox::critical(this,tr("درج شعر جدید"),tr("شعر اضافه شد"));
}
}
mainwindow.connClose();

How to write Sqlite DataBase in Qt

I am using this code for creating SQlite Database in Qt.
Now I have 2 questions: First how can I add new record in table , and second how can I check the table exist?
bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("SQLITE");
db.setHostName("Server");
db.setDatabaseName("Message.DB");
if (!db.open()) {
QMessageBox::critical(0, QObject::tr("Database Error"),
db.lastError().text());
return false;
}
Should be able to work:
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName("Message.DB");
if(database.open() == false) {
// ... <- Error handling
return false;
}
QSqlQuery sqlQuery(database);
bool inserted = sqlQuery.exec("INSERT INTO my_table (col1, col2) VALUES (\'one\', \'two\')");
if(inserted == false) {
// ... <- Error handling
}
Not sure how to check if table exists but to create a table if it does not already exist you can do:
bool created = sqlQuery.exec("CREATE TABLE IF NOT EXISTS my_table(<column info>);");
You should also create query which will create not empty database and use correct name of variable(in your code you use dbConnection firstly and after that - db.

Can't execute mysql querys with QT

I'm trying to connect and execute a query with the QT framework, I can connect to the mysql db and I have tested the query and verified it works on the database. I think the mysql driver is correctly installed because I can connect and it doesn't throw any errors
void Login::on_loginButton_clicked()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("127.0.0.1");
db.setDatabaseName("TestBase");
db.setUserName("username");
db.setPassword("password");
if (!db.open()) {
QMessageBox::critical(0,"Database Error","Could not connect to the database, check your internet connection.");
}
QSqlQuery data("SELECT * FROM `TestBase`.`Users` WHERE `userName` = 'Afonso'");
//data.exec("SELECT * FROM `TestBase`.`Users` WHERE `userName` = 'Afonso'");
QMessageBox::information(NULL, "Query executed", "The query returned: " + data.exec());
}
I have also tried with
data.exec("insert query here");
data.next();
Nothing seems to work
I am trying to display the result of the query in a QMessageBox
QSqlQuery query(db);
query.prepare("SELECT * FROM `TestBase`.`Users` WHERE `userName` = :user_name");
query.bindValue(":user_name", "Afonso");
if (!query.exec())
{
qDebug() << query.lastError().text();
retrun;
}
while (query.next())
{
QVariant v = query.value(0);
}
I use pyqt but in general with a select query, I start to get data with
.first() rather than .exec() .exec_() in pyqt.
After that next() works just fine.