cannot name connection in qt - c++

QSqlDatabase db;
DBCONNECTION( QString conName)
{
db.addDatabase("QMYSQL",conName);
db.setDatabaseName("mitsubishi");
db.setHostName("localhost");
db.setUserName("root");
db.setPassword("");
qDebug()<<db.connectionName()<<conName;
}
db.connectionName returns empty string
but conName returns "string"
whats the problem?
and while executing query driver is not loaded

QSqlDatabase::addDatabase is a static function which returns a QSqlDatabase object. So it is not doing anything to your existing QSqlDatabase object. How you should use it:
db = QSqlDatabase::addDatabase("QMYSQL", conName);

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

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.

QSqlDatabasePrivate::removeDatabase: connection 'myConnectionName' is still in use, all queries will cease to work

I have a folder where i have a many databases. Some times may be deleted or added database to the folder.
So I use QTimer and read all databases.
It is a my code:
this->timer = new QTimer(this);
this->timer->setInterval(15000);
connect(this->timer, &QTimer::timeout, this, [=]() {
QString path = "C:\\Users\\User\\Desktop\\DAXI SMS SENDER\\SMSSenderAllBASE";
//QString path = qApp->applicationDirPath() + "\\SMSSenderAllBASE";
QDir recoredDir(path);
QStringList allFiles = recoredDir.entryList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst);
for (int i = 0; i < allFiles.size(); i++) {
QString fullPath = path + "\\" + allFiles[i];
QString connectionName = allFiles[i];
connectionName = connectionName.remove(connectionName.size() - 4, 4);
QSqlDatabase db = QSqlDatabase::addDatabase("QIBASE", connectionName);
db.setDatabaseName(fullPath);
db.setHostName("localhost");
db.setPort(3050);
db.setUserName("SYSDBA");
db.setPassword("masterkey");
thrdHelperSendSMS *help = new thrdHelperSendSMS(db, this);
connect(help, &thrdHelperSendSMS::helperFinished, this, [=](QString connectionName){
QSqlDatabase t_db = QSqlDatabase::database(connectionName);
t_db.close();
QSqlDatabase::removeDatabase(connectionName);
delete help;
});
help->run();
}
});
this->timer->start();
Yes I'm sure that the helperFinished signal will happen and this time I will not have any connection with this base.
EDIT:
If i remove
thrdHelperSendSMS *help = new thrdHelperSendSMS(db, this);
connect(help, &thrdHelperSendSMS::helperFinished, this, [=](QString connectionName){
QSqlDatabase t_db = QSqlDatabase::database(connectionName);
t_db.close();
QSqlDatabase::removeDatabase(connectionName);
delete help;
});
help->run();
example:
for (int i = 0; i < allFiles.size(); i++) {
QString fullPath = path + "\\" + allFiles[i];
QString connectionName = allFiles[i];
connectionName = connectionName.remove(connectionName.size() - 4, 4);
QSqlDatabase db = QSqlDatabase::addDatabase("QIBASE", connectionName);
db.setDatabaseName(fullPath);
db.setHostName("localhost");
db.setPort(3050);
db.setUserName("SYSDBA");
db.setPassword("masterkey");
QSqlDatabase::removeDatabase(connectionName);
}
I have the same error.
You don't use removeDatabase() correctly. The object of SqlDatabase needs to go out of scope first. See documentation.
Wrong use
QSqlDatabase db = QSqlDatabase::database("sales");
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
QSqlDatabase::removeDatabase("sales"); // will output a warning
Correct use
{
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
In the second example db will go out of scope after } and you will no longer see the error message QSqlDatabasePrivate::removeDatabase: connection 'myConnectionName' is still in use, all queries will cease to work
Please read the documentation carefully. The database stuff is sensible and every line needs to be checked carefully.
Also you have missing db.close(); - It makes sense to close the database before you remove it.
#user3606329's answer is right, but I add this possibility:
QSqlDatabase db = QSqlDatabase::database("sales");
{
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
//use query
}
db = QSqlDatabase();
QSqlDatabase::removeDatabase("sales");
You can use std::swap to force it destruct on demand.
I basically use BOOST_SCOPE_EXIT for cases when want to call a function on scope exit including not expected exit like through an exception throw.
#include <boost/scope_exit.hpp>
{
QSqlDatabase db;
BOOST_SCOPE_EXIT(this_, &db) { // by reference, otherwise it will copy a stack object
// access object here through the this_ instead of this ...
if (db.isOpen()) {
db.close(); // closing if not yet closed before connection remove
}
std::swap(db, QSqlDatabase{}); // destruct via swap
// CAUTION:
// From this point you must not call to `QSqlDatabase::database("MYDB", ...)`, otherwise it will return another constructed object!
//
QSqlDatabase::removeDatabase("MYDB");
} BOOST_SCOPE_EXIT_END
// ui change from here ...
// accomplish last ui changes before long blocking operation
qApp->processEvents();
db = QSqlDatabase::addDatabase("...", "MYDB");
// database access from here ...
}
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "conn_name");
db.open();
if (db.open())
{
qDebug()<<"DataBase is Open";
}
else
{
qDebug()<<"DataBase is Not Open";
}
QSqlQueryModel * model = new QSqlQueryModel();
QSqlQuery query(QSqlDatabase::database("conn_name"));
query.exec("SMTHING")
if (query.exec())
{
while (query.next())
{
ui->QTableView->setModel(model);
model->setHeaderData(2, Qt::Horizontal, QObject::tr("????"));
}
}
db.close();
QSqlDatabase::removeDatabase("conn_name");
Here is my code

SQLite remove database error

I have widget which connects to database:
Widget::Widget(QWidget *parent)
{
QString databaseName = "name";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(databaseName);
db.setHostName("localhost");
if(!db.open())
qDebug()<<"ret error";
}
Now I want to delete database connection after widget close (currently I get warnings like: QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection is still in use...). I' ve read some topics and tried to evaluate some solution from them but none works for me. My code:
void Widget::closeEvent(QCloseEvent *e)
{
QSqlDatabase db = QSqlDatabase::database();
QString connection = db.connectionName();
db.close();
QSqlDatabase::removeDatabase(connection);
qDebug()<<"error: "<<db.lastError().text();
}
Error I get is: Driver not loaded Driver not loaded
What is the correct way to do this?
Edit:
another method:
void Widget::someMethod()
{
QSqlDatabase db = QSqlDatabase::database();
QSqlQuery query(db);
query.exec("some query");
}
Try giving a connection name parameter(2nd parameter) in addDatabase() , that should solve your problem.
Here is the modified code you could try:
Widget::Widget(QWidget *parent)
{
QString databaseName = "name";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "test_db_connection" );
db.setDatabaseName(databaseName);
db.setHostName("localhost");
if(!db.open())
qDebug()<<"ret error";
}
Here is a complete working code from my machine for sqlite database which you can use as reference:
local_db = QSqlDatabase::addDatabase("QSQLITE","localdb");
local_db.setDatabaseName("localdb.sqlite");
local_db_query = QSqlQuery(local_db);
local_db_query.prepare( "SELECT * FROM sample_table" );
local_db_query.exec();