Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Mobile and Embedded
  4. [SOLVED] Problem with QSqlDatabase
Forum Update on Monday, May 27th 2025

[SOLVED] Problem with QSqlDatabase

Scheduled Pinned Locked Moved Mobile and Embedded
27 Posts 6 Posters 29.4k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    joonne
    wrote on 18 Dec 2013, 12:15 last edited by
    #1

    Hi,

    this is my very first post here and I think that it is fine to start a new thread for this problem because i have been searching for an aswer for 2 days now. I'm working with a little project where I am using sqlite database, which I created and I am not getting it to work. I have been working with databases only since this week's monday so there is much that I don't know yet but I am eager to learn.

    So here is the code and hopefully someone can point me to right direction with it:

    @bool User::getUser() {
    bool ret = false;
    db_ = QSqlDatabase::addDatabase("QSQLITE","userConnection");
    db_.setDatabaseName("C:/Users/Jonne/Desktop/userDatabase.db.sqlite");

     // Some testing for the file
    QFileInfo fi("C:/Users/Jonne/Desktop/userDatabase.db.sqlite");
    if(QFile::exists("C:/Users/Jonne/Desktop/userDatabase.db.sqlite")) {
         qDebug() << fi.filePath();
     }
    
    if(db_.Open()) {
    
        qDebug() << "Database open.";
    
        QSqlQuery query("SELECT * FROM user;",db_);
        qDebug() << query.lastError();
    
        if (query.first()) {
    
            name_ = query.value(1).toString();
            age_ = query.value(2).toInt();
            gender_ = query.value(3).toString();
            height_ = query.value(4).toDouble();
            weight_ = query.value(5).toDouble();
            ret = true;
        }
    
    } 
    
    db_.close();
    return ret;
    

    }@

    With this code I am getting these outputs and errors:

    @"userConnection"
    QSqlError(-1, "Error opening database", "out of memory")
    QSqlDatabasePrivate::removeDatabase: connection 'userConnection' is still in use, all queries will cease to work.
    QSqlDatabasePrivate::addDatabase: duplicate connection name 'userConnection', old connection removed.
    "userConnection"
    QSqlError(-1, "Error opening database", "out of memory")
    QSqlDatabasePrivate::removeDatabase: connection 'userConnection' is still in use, all queries will cease to work.
    QSqlDatabasePrivate::addDatabase: duplicate connection name 'userConnection', old connection removed.
    "userConnection"
    QSqlError(-1, "Error opening database", "out of memory") @

    I don't for example understand why these errors are coming 3 times. I am getting the database from Desktop because I couldn't get it from the project directory.

    Earlier I got a error message which said that there is not table named user in the database and that was when I tried to load the database from the project folder. Also I have a problem with qt-creator itself because as default it puts build and source files in the same directory and I couldn't get it to change the build directory.

    Thanks in advance for any help. :)

    1 Reply Last reply
    0
    • S Offline
      S Offline
      stoyanps
      wrote on 18 Dec 2013, 12:49 last edited by
      #2

      About 3 times messages, I guess it is because somewhere in your program you call function getUser() at least three times. First time connection is created and every next time it is removed and created again.

      The error "QSqlError(-1, "Error opening database", "out of memory")" can be caused by location of your database. In Windows 7 for folders under "Users" there are limited access rights. It is possible that your program have no right to create and/or modify database on this location. I suggest to change location of database to "C:\Test\userDatabase.db.sqlite" for example or some other folder.

      1 Reply Last reply
      0
      • J Offline
        J Offline
        joonne
        wrote on 18 Dec 2013, 19:12 last edited by
        #3

        That is the weird part because I am pretty sure that I call the getUser() function only 1 time but I don't know why the output looks like that. I changed the location of database as you suggested but the error message is still the same.

        1 Reply Last reply
        0
        • S Offline
          S Offline
          SGaist
          Lifetime Qt Champion
          wrote on 18 Dec 2013, 20:34 last edited by
          #4

          Hi and welcome to devnet,

          First thing you should do is open your database connection only once at the start of your program since you are using SQLite. Then, if getUser is a slot, verify that you don't connect to it several times.

          Hope it helps

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply
          1
          • P Offline
            P Offline
            panosk
            wrote on 18 Dec 2013, 20:36 last edited by
            #5

            Line 12 should be
            @
            if(db_.open()) { //lowercase "o"
            @

            1 Reply Last reply
            0
            • J Offline
              J Offline
              joonne
              wrote on 18 Dec 2013, 20:37 last edited by
              #6

              So it would be a good way to make separate functions for example openDB() and something like that? Thanks I will give it a try.

              Thanks to panoski also for pointing the mistake, I forgot it because I modified the code a bit.

              1 Reply Last reply
              0
              • J Offline
                J Offline
                joonne
                wrote on 18 Dec 2013, 21:27 last edited by
                #7

                I made separate function for opening the database and I call it at the begin of my program and it solved other problems except the one that matters the most so it doesn't open the database. The error messages in the output are: @QSqlError(-1, "Error opening database", "out of memory")
                Unable to open input file: No such file or directory@

                Is there something wrong with my path or what could cause this?

                I am now using this code to open the database:

                @bool User::openDB() {

                // Find QSLite driver
                db_ = QSqlDatabase::addDatabase("QSQLITE");
                db_.setDatabaseName("C:/Databases/userDatabase.db.sqlite");
                
                // Open databasee
                if(db_.open()) {
                    return true;
                } else {
                    qDebug() << db_.lastError();
                    return false;
                }
                

                }@

                1 Reply Last reply
                0
                • S Offline
                  S Offline
                  SGaist
                  Lifetime Qt Champion
                  wrote on 18 Dec 2013, 21:29 last edited by
                  #8

                  How big is your database ?

                  Interested in AI ? www.idiap.ch
                  Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                  1 Reply Last reply
                  0
                  • J Offline
                    J Offline
                    joonne
                    wrote on 18 Dec 2013, 21:33 last edited by
                    #9

                    The database is 2kB and contains only 1 row of User's information such as name and age.

                    1 Reply Last reply
                    0
                    • P Offline
                      P Offline
                      panosk
                      wrote on 18 Dec 2013, 21:42 last edited by
                      #10

                      And how did you modify the User::getUser() function?

                      1 Reply Last reply
                      0
                      • J Offline
                        J Offline
                        joonne
                        wrote on 18 Dec 2013, 21:44 last edited by
                        #11

                        The function is now like this:

                        @bool User::getUser() {

                        bool ret = false;
                        
                        if(db_.isOpen()) {
                        
                            QSqlQuery query("SELECT * FROM user;",db_);
                            qDebug() << query.lastError();
                        
                            if (query.first()) {
                        
                                name_ = query.value(1).toString();
                                age_ = query.value(2).toInt();
                                gender_ = query.value(3).toString();
                                height_ = query.value(4).toDouble();
                                weight_ = query.value(5).toDouble();
                                ret = true;
                            }
                        }
                        
                        return ret;
                        

                        }@

                        1 Reply Last reply
                        0
                        • J Offline
                          J Offline
                          joonne
                          wrote on 18 Dec 2013, 21:58 last edited by
                          #12

                          And I think I should have specified before but I am making a Sailfish application here, does that affect to your advice a lot? Sorry if this was a vital information :/

                          1 Reply Last reply
                          0
                          • P Offline
                            P Offline
                            panosk
                            wrote on 18 Dec 2013, 22:04 last edited by
                            #13

                            I remember a post where a user had trouble with this QSqlQuery constructor. Try to change your function like this:
                            @
                            bool User::getUser() {

                            bool ret = false;
                            
                            if(db_.isOpen()) {
                            
                                QSqlQuery query(db_);
                                if(!query.exec&#40;"SELECT * FROM user"&#41;)
                                    qDebug() << query.lastError();
                            
                                if (query.first()) {
                            
                                    name_ = query.value(1).toString();
                                    age_ = query.value(2).toInt();
                                    gender_ = query.value(3).toString();
                                    height_ = query.value(4).toDouble();
                                    weight_ = query.value(5).toDouble();
                                    ret = true;
                                }
                            }
                            
                            return ret;
                            

                            }
                            @

                            1 Reply Last reply
                            0
                            • J Offline
                              J Offline
                              joonne
                              wrote on 18 Dec 2013, 22:18 last edited by
                              #14

                              I changed the function like you said but the database isn't open so I cant test this but it looks better, thanks.

                              1 Reply Last reply
                              0
                              • P Offline
                                P Offline
                                panosk
                                wrote on 18 Dec 2013, 22:29 last edited by
                                #15

                                Of course, the error prints when opening the database.... Anyway, I suppose you have also double-checked that the path and database file name are accurate.

                                1 Reply Last reply
                                0
                                • S Offline
                                  S Offline
                                  SGaist
                                  Lifetime Qt Champion
                                  wrote on 18 Dec 2013, 22:29 last edited by
                                  #16

                                  Indeed you should have mention that earlier. Are you running this application on your Windows computer or on the Sailfish emulator/device ? In the second case I don't think it will access your hard drive to get the file hence the error "no such file or directory"

                                  Interested in AI ? www.idiap.ch
                                  Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                                  1 Reply Last reply
                                  0
                                  • S Offline
                                    S Offline
                                    stoyanps
                                    wrote on 18 Dec 2013, 22:50 last edited by
                                    #17

                                    First in function OpenDB add this:
                                    @ if(db_.open()) {
                                    QStringList tables = db_.tables();
                                    qDebug() << "Tables: " << tables;
                                    return true;
                                    } else {@

                                    This will show you all tables in your database if connection is successful.

                                    1. In the beginning of function getUser add this:
                                      @QSqlDatabase db_ = QSqlDatabase::database();
                                      if(db_.isOpen()) {
                                      QSqlQuery query(db_);@
                                    1 Reply Last reply
                                    0
                                    • J Offline
                                      J Offline
                                      joonne
                                      wrote on 19 Dec 2013, 05:42 last edited by
                                      #18

                                      Thanks for replies. I am running the application in Sailfish emulator and I think I should now get familiar with the usage of local storage and how to get database available for my Sailfish application. After that I can continue with these comments you have given.

                                      1 Reply Last reply
                                      0
                                      • J Offline
                                        J Offline
                                        joonne
                                        wrote on 19 Dec 2013, 06:50 last edited by
                                        #19

                                        I am a bit confused now. Does someone know how I could store my existing database to local storage and how I could refer to it and use it from my c++ class/object? I did found some examples on how to access database from QML but I would like to access my database from the c++ backend.

                                        1 Reply Last reply
                                        0
                                        • P Offline
                                          P Offline
                                          p3c0
                                          Moderators
                                          wrote on 19 Dec 2013, 07:14 last edited by
                                          #20

                                          Hi,

                                          This test code might help you

                                          @
                                          MainWindow::MainWindow(QWidget *parent) :
                                          QMainWindow(parent),
                                          ui(new Ui::MainWindow)
                                          {
                                          ui->setupUi(this);

                                          if(ConnectLocalDB())
                                              GetData();
                                          

                                          }

                                          MainWindow::~MainWindow()
                                          {
                                          delete ui;
                                          }

                                          bool MainWindow::ConnectLocalDB()
                                          {
                                          db = QSqlDatabase::addDatabase("QSQLITE");

                                          QString dbpath = "/root/testd.db";
                                          db.setDatabaseName(dbpath);
                                          
                                          QSqlQuery query(QSqlDatabase::database());
                                          query.exec&#40;"CREATE TABLE testtable ("
                                                     "id  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                                                     "testcolumn TEXT&#41;;"
                                                     );
                                          
                                          query.exec&#40;"insert into testtable(testcolumn&#41; values('one')");
                                          query.exec&#40;"insert into testtable(testcolumn&#41; values('two')");
                                          query.exec&#40;"insert into testtable(testcolumn&#41; values('three')");
                                          
                                          qDebug() << dbpath;
                                          
                                          return db.open();
                                          

                                          }

                                          bool MainWindow::GetData()
                                          {
                                          QSqlQuery query(QSqlDatabase::database());
                                          QString q = "select * from testtable;";
                                          query.exec(q);
                                          while(query.next())
                                          {
                                          qDebug() << query.value(1).toString();
                                          }
                                          }
                                          @

                                          157

                                          1 Reply Last reply
                                          0

                                          10/27

                                          18 Dec 2013, 21:42

                                          17 unread
                                          • Login

                                          • Login or register to search.
                                          10 out of 27
                                          • First post
                                            10/27
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved