How to write Sqlite DataBase in Qt - c++

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.

Related

QSqlQuery 'Parameter Count Mismatch'

I am trying to take data from six fields on a form and pass the data the user enters into a database (A local SQLite3 database). The ID is an integer and the primary key and the rest are varchars of enough length. After reading a lot of related questions, I still cannot figure out where my code is going wrong. I have confirmation that the program is connected to the database, but I keep getting 'parameter count mismatch'. Where am I going wrong? I'm using Qt 5.15 and C++. The table TOOL exists, as I have it open in SQLite Manager with a test row already inserted.
Below is the function that is supposed to submit the data:
//passes data to database upon clicking submit button
void Add_item::on_submitButton_clicked() {
QString name, location, safety, summary, uses, idNumber;
idNumber = ui->testIdBox->text();
name = ui->nameField->text();
location = ui->locationField->text();
safety = ui->safetyField->text();
summary = ui->summaryField->text();
uses = ui->useField->text();
QSqlQuery qry;
qry.prepare("INSERT INTO TOOLS (TOOL_ID, TOOL_NAME, TOOL_SUMMARY, TOOL_LOCATION, TOOL_USE, TOOL_SAFETY) "
"VALUES (:idNumber, :name, :summary, :location, :uses, :safety)");
//binding all values to prevent sql injection attacks
qry.bindValue(":idNumber", idNumber);
qry.bindValue(":name", name);
qry.bindValue(":summary", summary);
qry.bindValue(":location", location);
qry.bindValue(":uses", uses);
qry.bindValue(":safety", safety);
if(qry.exec()){
QMessageBox::critical(this,tr("Confirmation Message"),tr("Success!"));
}
else {
QMessageBox::critical(this,tr("Confirmation Message"),tr("Error, data was not saved."), qry.lastError().text());
}
connClose();
}
Here is where I connect to the database:
//connecting to database
bool Add_item::connOpen() {
QSqlDatabase mydb = QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("C:/Users/laesc/OneDrive/Documents/ToolBuddy/test.db");
if (mydb.open()) {
ui->statusLabel->setText("Connected!");
qDebug()<<("Connected");
return true;
}
else {
ui->statusLabel->setText("Connection Not Successful...");
qDebug()<<("Not Connected");
return false;
}
}
For future viewers, I ended up reducing the number of parameters to 2 and the query worked. For one reason or another the query didn't work if I tried to bind more than 2 variables. I'm just doing multiple queries.

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

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.

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

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.