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

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)");

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.

How to deal: QSqlQuery::exec() returns false

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.

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.

Qt Sqlite table column appears to be gone

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":temp:");
if (!db.open()) {
qDebug() << "Database open error." << db.lastError();
return;
}
QSqlQuery query(db);
query.prepare("create table if not exists dew (id int, title varchar(255) not null)");
if (!query.exec()) {
qDebug() << "Query exec error. " << query.lastError();
return;
}
qDebug() << "Insert query exec OK";
if (!query.exec("insert into dew(id, title) values (1, 'hello')")) qDebug() << query.lastError();
Shows the output as
Insert query exec OK
QSqlError(1, "Unable to execute statement", "table dew has no column named id")
Insertion finished.
Table creation seems to be OK. But where is id field? I'm confused with this code. I test query.record().contains("id"); and it is false
":temp:" is not a valid name for a temporary database, this creates a regular database on disk which stays after the database connection is closed.
To create a temporary or an in-memory sqlite database, that won't be saved to a file, you need to pass respectively an empty string (*) or the special string ":memory:" as the database name.
http://www.sqlite.org/inmemorydb.html
Qt doesn't allow an empty QString as the database name, but a QString starting with a '\0' should work: db.setDatabaseName(QChar(0));