Qsqlquery exec database not open ошибка

I’m working on qt, my database was rightly connected with qt but suddenly i have the following problem every time i debug,,,i i become not able to fetch or to add data from/to the database,,, i don’t know whats’s the matter but i’m new to qt.

QSqlQuery::exec: database not open

could anybody help please ,,it’s an emergency case
here the code

db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=C:/Users/user/Desktop/Final_Version/db.accdb");
db.close();
db.open();
QSqlQuery query;
query.exec("Select ID from TestId");
while(query.next())
{
 TestId = query.value(0).toInt();
}
db.close();
//==================================================================================

RAM's user avatar

RAM

2,3122 gold badges20 silver badges44 bronze badges

asked Jun 1, 2013 at 1:09

Nermeeno Alami's user avatar

QSqlQuery *query = new QSqlQuery(db);

I think that can help you! :)

Linga's user avatar

Linga

10.4k10 gold badges52 silver badges105 bronze badges

answered Jan 28, 2014 at 11:22

darialarionova's user avatar

0

You need to add qsql dll files for Microsoft Access Driver within your sqldrivers folder

Check following if you are debugging

  1. check your project settings for dll reference(in .pro file of your project, you have to put QT += sql, if you are using Visual studio integration you check reference in project settings form properties)
  2. check you Qtdirectory for driver folder and dll’s

If you are distributing your app, you just copy sql driver folder also with your executable along with required dlls.

edit your QSqlQuery object binded with database connection

db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb};FIL={MSAccess};DBQ=C:/Users/user/Desktop/Final_Version/db.mdb");
database.open();
QSqlQuery query(db);
query.exec("Select ID from TestId");
while(query.next())
{
    TestId = query.value(0).toInt();
}
db.close();

I think, some of this will help you… :)

RAM's user avatar

RAM

2,3122 gold badges20 silver badges44 bronze badges

answered Jun 1, 2013 at 9:57

imalvare's user avatar

imalvareimalvare

2951 silver badge13 bronze badges

3

try not to use db.open() check the database opened or not. It’s not that accurate,
check this out, after the check you might be able use db.open() and exec(command) normally(link with query first).

QSqlQueryModel *model = new QSqlQueryModel;
if (db.isValid())
{
    db.open();
    if (db.isOpen())
    {
        QSqlQuery query(db);
        query.prepare("SELECT * FROM version_chart");
        query.exec();
        if (query.isActive())
        {
            model->setQuery(query);
            db.close();
            qDebug() << "opened success\n";
        }
        else {
            qDebug() << "query is not active:DB being occupied, close manually";
            qDebug() << db.lastError().text();
            qFatal("failed to connect.");
            return false;
        }
    }
    else {
        qDebug() << "DB is not open";
        return false;
    }
}
else {
    qDebug() << "DB is not valid";
    return false;
}

Here’s also another way I’m using right now.
I may simply change the file name and check if it succeed.

if (isFileUsed(origin_path))
    {
        qDebug() << "Warning: File being occupied!" << "\n";
        QMessageBox::critical(0,"File Open Error", "File occupied, please close and retry!",
            QMessageBox::Ok, 0);
        return false;
    }

bool Save_DB::isFileUsed(QString fpath)
{
    bool isUsed = false;

    QString fpathx = fpath + "x";

    QFile file(fpath);
    bool isExist = file.exists();
    if (isExist == true)
    {
        bool isCanRename = file.rename(fpath, fpathx);
        if (isCanRename == false)
        {
            isUsed = true;
        }
        else
        {
            file.rename(fpathx, fpath);
        }
    }
    file.close();

    return isUsed;
}

answered Mar 14, 2022 at 1:51

Battery Eyes WUW's user avatar

I’m working on qt, my database was rightly connected with qt but suddenly i have the following problem every time i debug,,,i i become not able to fetch or to add data from/to the database,,, i don’t know whats’s the matter but i’m new to qt.

QSqlQuery::exec: database not open

could anybody help please ,,it’s an emergency case
here the code

db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=C:/Users/user/Desktop/Final_Version/db.accdb");
db.close();
db.open();
QSqlQuery query;
query.exec("Select ID from TestId");
while(query.next())
{
 TestId = query.value(0).toInt();
}
db.close();
//==================================================================================

RAM's user avatar

RAM

2,3122 gold badges20 silver badges44 bronze badges

asked Jun 1, 2013 at 1:09

Nermeeno Alami's user avatar

QSqlQuery *query = new QSqlQuery(db);

I think that can help you! :)

Linga's user avatar

Linga

10.4k10 gold badges52 silver badges105 bronze badges

answered Jan 28, 2014 at 11:22

darialarionova's user avatar

0

You need to add qsql dll files for Microsoft Access Driver within your sqldrivers folder

Check following if you are debugging

  1. check your project settings for dll reference(in .pro file of your project, you have to put QT += sql, if you are using Visual studio integration you check reference in project settings form properties)
  2. check you Qtdirectory for driver folder and dll’s

If you are distributing your app, you just copy sql driver folder also with your executable along with required dlls.

edit your QSqlQuery object binded with database connection

db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb};FIL={MSAccess};DBQ=C:/Users/user/Desktop/Final_Version/db.mdb");
database.open();
QSqlQuery query(db);
query.exec("Select ID from TestId");
while(query.next())
{
    TestId = query.value(0).toInt();
}
db.close();

I think, some of this will help you… :)

RAM's user avatar

RAM

2,3122 gold badges20 silver badges44 bronze badges

answered Jun 1, 2013 at 9:57

imalvare's user avatar

imalvareimalvare

2951 silver badge13 bronze badges

3

try not to use db.open() check the database opened or not. It’s not that accurate,
check this out, after the check you might be able use db.open() and exec(command) normally(link with query first).

QSqlQueryModel *model = new QSqlQueryModel;
if (db.isValid())
{
    db.open();
    if (db.isOpen())
    {
        QSqlQuery query(db);
        query.prepare("SELECT * FROM version_chart");
        query.exec();
        if (query.isActive())
        {
            model->setQuery(query);
            db.close();
            qDebug() << "opened success\n";
        }
        else {
            qDebug() << "query is not active:DB being occupied, close manually";
            qDebug() << db.lastError().text();
            qFatal("failed to connect.");
            return false;
        }
    }
    else {
        qDebug() << "DB is not open";
        return false;
    }
}
else {
    qDebug() << "DB is not valid";
    return false;
}

Here’s also another way I’m using right now.
I may simply change the file name and check if it succeed.

if (isFileUsed(origin_path))
    {
        qDebug() << "Warning: File being occupied!" << "\n";
        QMessageBox::critical(0,"File Open Error", "File occupied, please close and retry!",
            QMessageBox::Ok, 0);
        return false;
    }

bool Save_DB::isFileUsed(QString fpath)
{
    bool isUsed = false;

    QString fpathx = fpath + "x";

    QFile file(fpath);
    bool isExist = file.exists();
    if (isExist == true)
    {
        bool isCanRename = file.rename(fpath, fpathx);
        if (isCanRename == false)
        {
            isUsed = true;
        }
        else
        {
            file.rename(fpathx, fpath);
        }
    }
    file.close();

    return isUsed;
}

answered Mar 14, 2022 at 1:51

Battery Eyes WUW's user avatar

This topic has been deleted. Only users with topic management privileges can see it.

  • Hello,

    So I have been receiving this error while running the following code

    void MainWindow::on_serachBox_textEdited(const QString& arg1) {
      // TODO: fix this
      // databse::exec: databse not open
      queryModel.setQuery("SELECT * FROM " + ui->comboBox->currentText() +
                              " WHERE " +
                              handler->getMainField(ui->comboBox->currentText()) +
                              " LIKE \'%" + arg1 + "%\'",
                          handler->getDB());
      qDebug() << queryModel.lastError();
      qDebug() << queryModel.query().lastQuery();
      ui->dataOutput->setModel(&queryModel);
    }
    

    This method runs when the text in line edit changed. I tried doing db->open(); before running thequeryModel.setQuery(…); but got no different result.
    What is really frustrating is when I run the following code, it runs without an issue:

    void MainWindow::updateQuery() {
      handler->open();
      queryModel.setQuery("SELECT * FROM " + ui->comboBox->currentText() +
                          " WHERE 1");
      handler->close();
      ui->dataOutput->setModel(&queryModel);
    }
    

    Can someone explain to me why I am getting this error and how I can fix it?

    Thank you.

    Application output:

    QSqlQuery::exec: database not open
    QSqlError("", "", "")
    "SELECT * FROM test1 WHERE testF_T LIKE '%3%'"
    

    PS.
    The query itself is fine, I checked it

  • @Omar-Alkersh

    Hi and welcome to devnet forum

    There is not need to have a pointer for the db. You can simply open the default as it is shown in the detailed description here. However, you have to open the db prior to access.

  • Hi and welcome to devnet,

    To add to @koahnig, what is that handler object ?

  • @SGaist just a normal object where I keep all my db related methods and object, QSqlQuery, QSqlDatabse etc.I

  • @koahnig I open it at the constructor of the handler object, an object where I keep all the db related methods and vars, to keep things clean

  • @Omar-Alkersh

    the only difference between the 2 code examples you posted is, that in one you pass the database to the queryModel.

    You said you tested it, and it did not work, what exactly is the result when you would change the function to this:

    void MainWindow::on_serachBox_textEdited(const QString& arg1) {
    
    handler->open();
      queryModel.setQuery("SELECT * FROM " + ui->comboBox->currentText() +
                              " WHERE " +
                              handler->getMainField(ui->comboBox->currentText()) +
                              " LIKE \'%" + arg1 + "%\'");
      qDebug() << queryModel.lastError();
      qDebug() << queryModel.query().lastQuery();
      handler->close();
      ui->dataOutput->setModel(&queryModel);
    }
    

    I haven’t used the QSqlQueryModel class myself yet, but are you supposed to to piece the query together like this!? Seems wrong.

  • @J.Hilk hello,
    The result is that I get the same meessge, QSqlQuery::exec: database not open, regardless whether I write handler->ope (); or not.
    The QTableView, which I use this model with, would stop displaying any table.

    Basically no difference.

  • @Omar-Alkersh Can you show the content of handler->open() ?

  • @jsulm

    
    QSqlDatabase db; //initialised in constructor
    
    void BDHandler::open (){
    db->open ();
    }
    
    handler->close (); //same as open
    
  • @Omar-Alkersh said in QSQlQuery::exec: database not open:

    QSqlDatabase db;

    If this is like this in the constructor then it is a local variable in the constructor and not related to the db pointer!
    You also should check the return value of db->open () and print out the output of http://doc.qt.io/qt-4.8/qsqldatabase.html#lastError in case it returns false. Also you did not say how you set up your database.

  • @jsulm

    Thanks for the suggestion but this is a global variable, it is just initialized in the constructor.

    And this is how I set up my db

    DBHandler::DBHandler(MainWindow* mWindow) {
      // init vars
      path = databaseloc.currentPath() + "/database";
      TABLE_MAIN = "main_table";
      COLUMN_ID = "_id";
      COLUMN_MAIN_NAME = "main_name";
    
      // check if dir exits
      QFileInfo fileInfo(path);
      if (!fileInfo.exists()) {
        if (databaseloc.mkpath(path)) {
          mWindow->close();
        }
      }
    
      // db name and loc
      path += "/" + dbName + ".db";
    
      // add db
      db = QSqlDatabase::addDatabase("QSQLITE");
      db.setDatabaseName(path);
    
      // open test, sets up query and creates mainTable if not exists
      if (db.open()) {
        query = QSqlQuery(db);
        query.exec("CREATE TABLE IF NOT EXISTS " + TABLE_MAIN + "(" + COLUMN_ID +
                   " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_MAIN_NAME +
                   " TEXT, mainField TEXT);");
    
      } else {
        // stop programme from continueing
        QMessageBox::StandardButton reply;
    
        reply = QMessageBox::warning(
            mWindow, "Error",
            "Was not able to open database file.\n" + db.lastError().text());
    
        if (reply == QMessageBox::Ok) {
          // exits with error
          exit(1);
        }
      }
      db.close();
    }
    
    
  • @Omar-Alkersh

    Did you notice the close at the end of your constructor?

     }
      db.close();
    }
    

    I guess there is your problem.

  • Hi,

    To add to @koahnig, why are you opening and closing the database connection again and again ?

  • @SGaist Thank you good sir. It worked. I thought that I should always close the db to stop any memory leaks. I used to develop android and I used to always close it after me.

    Solution was not to close the db. Obviously.

  • AFAIK, there’s no known memory leaks in Qt’s SQL drivers.

    Don’t get me wrong, there might be good reasons to only open a database connection when needed however this requires a bit more architecture to make it work correctly.

Михаиллл

Qt, SQLite

Добрый день.

Я создал  в SQLiteStudio базу данных.

Пытаюсь открыть ее в QT этим кодом

QSqlDatabase ResumeDB; //resume sql
ResumeDB.setDatabaseName("C:\\CVReader\\ResumeArraySQLite.db");
if (!ResumeDB.open()) {qDebug()<<"not open";}

дебаг выдает «not open»

Не знаете, где ошибка и как открыть?

Do you like it? Share on social networks!

15

Comments

Only authorized users can post comments.
Please, Log in or Sign up

Last comments

IscanderChe

QScintilla C++ example По горячим следам (с другого форума вопрос задали, пришлось в памяти освежить всё) решил дополнить. Качаем исходники с https://riverbankcomputing.com/software/qscintilla/downlo…

Now discuss on the forum

NSProject

Помогите добавить Ajax в проект В принципе ничего сложного с отправкой на сервер нет. Всё что ты хочешь отобразить на странице передаётся в шаблон и рендерится. Ты просто создаёшь файл forms.py в нём описываешь свою форму и в …

BlinCT

BlinCTSept. 16, 2023, 12:35 a.m.

Размеры полей в TreeView Всем привет. Пытаюсь сделать дерево вот такого вида Пытаюсь организовать делегат для каждой строки в дереве. ТО есть отступ какого то размера и если при открытии есть под…

  1. 28th October 2009, 14:54


    #1

    Red face QSqlQuery::exec: database not open

    MY CODE :

    QSqlDatabase db;
    QSqlQuery query;

    db = QSqlDatabase::addDatabase(«QSQLITE»);
    db.setDatabaseName(«sampleDB.db»);
    if (db.open())
    {
    qDebug()<<«\n**** db opened**** :»;
    query.exec(«create table person (id int primary key, «
    «firstname varchar(20), lastname varchar(20))»);
    }

    OUTPUT:
    ***db opened***:
    QSqlQuery::exec: database not open

    Why i am getting error even after db.open() succeeded? why Table was not created?


  2. 28th October 2009, 16:38


    #2

    Default Re: QSqlQuery::exec: database not open

    When you create QSqlQuery object the default Database must already exist.

    Try with

    1. db.setDatabaseName("sampleDB.db");

    2. if (db.open())

    3. {

    4. qDebug()<<"\n**** db opened**** :";

    5. query.exec("create table person (id int primary key, "

    6. "firstname varchar(20), lastname varchar(20))");

    7. }

    To copy to clipboard, switch view to plain text mode 

    instead of

    1. db.setDatabaseName("sampleDB.db");

    2. if (db.open())

    3. {

    4. qDebug()<<"\n**** db opened**** :";

    5. query.exec("create table person (id int primary key, "

    6. "firstname varchar(20), lastname varchar(20))");

    7. }

    To copy to clipboard, switch view to plain text mode 

    Notice that QSqlQuery is created after QSqlDatabase::addDatabase

    A camel can go 14 days without drink,
    I can’t!!!


  3. 28th October 2009, 18:24


    #3

    Default Re: QSqlQuery::exec: database not open

    what was the problem with below code:

    query.exec(«create table person (id int primary key, «
    «firstname varchar(20), lastname varchar(20))»);
    query.exec(«insert into person values(101, ‘Danny’, ‘Young’)»);
    query.exec(«insert into person values(102, ‘Christine’, ‘Holand’)»);
    query.exec(«insert into person values(103, ‘Lars’, ‘Gordon’)»);
    query.exec(«insert into person values(104, ‘Roberto’, ‘Robitaille’)»);
    query.exec(«insert into person values(105, ‘Maria’, ‘Papadopoulos’)»);
    qDebug()<<query.executedQuery();

    Output should be «insert into person values(105, ‘Maria’, ‘Papadopoulos’)»
    but the output is «create table person (id int primary key, firstname varchar(20), lastname varchar(20))»

    Why remaining statements(second onwards) not exicuting..? I hope query.executedQuery() function gives recently exicuted query. The above example is from qt creator. Need explination please.


  4. 28th October 2009, 18:34


    #4

    Default Re: QSqlQuery::exec: database not open

    The function QSqlQuery::executedQuery() returns the last successfully executed query.

    You have probably an error executing insert queries.
    Test the return values of QSqlQuery::exec

    A camel can go 14 days without drink,
    I can’t!!!


  5. 28th October 2009, 18:45


    #5

    Default Re: QSqlQuery::exec: database not open

    yes yes….. all insert queries (query.exec(«insert….»)) returning success status(true), but output not coming as expected. its not printing last successfully executed query.


  6. 28th October 2009, 19:03


    #6

    Default Re: QSqlQuery::exec: database not open

    A camel can go 14 days without drink,
    I can’t!!!


  7. 28th October 2009, 19:16


    #7

    Default Re: QSqlQuery::exec: database not open

    Found answer…

    QSqlQuery::executedQuery()—>returning first successfully executed query.(correct me if i am wrong)
    If i use QSqlQuery::clear() after exicuting each QSqlQuery::exec() then only its giving last suuceessfully exicuted query.

    Why this is happening.. documents in qt were telling some thing other than realty..


  8. 29th October 2009, 08:01


    #8

    Default Re: QSqlQuery::exec: database not open

    Quote Originally Posted by newtowindows
    View Post

    Found answer…
    Why this is happening.. documents in qt were telling some thing other than realty..

    It’s Can be a Bug?

    A camel can go 14 days without drink,
    I can’t!!!


  9. 29th October 2009, 08:48


    #9

    Default Re: QSqlQuery::exec: database not open

    Maybe its a bug. Any expert’s views are helpfull for us


Понравилась статья? Поделить с друзьями:
  • Python ошибка при установке 0x80070659
  • Qt creator ошибка lnk2019
  • Python ошибка отступа неожиданный отступ
  • Python ошибка индекса
  • Qt creator настройки android содержат ошибки