Page 1 of 4 123 ... LastLast
Results 1 to 20 of 61

Thread: using an isntance of QSqlDatabase for connection defiinition

  1. #1
    jfinn88 Guest

    Default using an isntance of QSqlDatabase for connection defiinition

    I have a Sqlite database I need to connect to...

    Instead of running the connection code every-time my method is called I would like to create an instance of the QSqlDatabase class

    I'm new to QT and still learning C++

    my understanding the code will run more efficiently and will "clean up" the code as well and make it so only create a connection once unless needed

    if you can explain the how the instance of the class will allow me to do this that would be awesome

    ----------old way-----------
    Qt Code:
    1. void myClass::insertLogMessage(QString msg)
    2. {
    3. //---Contects to a database | Uses QSQLITE driver---//
    4. QSqlDatabase userEventDB = QSqlDatabase::addDatabase("QSQLITE");
    5. //---Sepcifies database path---//
    6. userEventDB.setDatabaseName("/home/amet/git/rnd/userLog.db");
    7. //---Checks if database is open---//
    8. if (userEventDB.open()) {
    9. qDebug() << "Connected to userEventLog database";
    10. }
    11. else {
    12. qDebug() << "Error: no connection was found!";
    13. }
    14. //---Opens database---//
    15. userEventDB.open();
    16.  
    17. qDebug() << "insert Log Message called";
    18. QSqlQuery query;
    19. query.prepare("INSERT INTO userlogevents (firstName, lastName, userName, eventMessage, dateTime) VALUES('John', 'Doe', 'JohnnyD', '"+msg+"', datetime(current_timestamp))");
    20. //---Executes Query Statement---//
    21. query.exec();
    22. }
    To copy to clipboard, switch view to plain text mode 



    ------using instance (QSqlDatabase) variable-----------
    Qt Code:
    1. void myClass::insertLogMessage(QString msg)
    2. {
    3. m_insertDataBase = QSqlDatabase::addDatabase("QSQLITE", "conn1");
    4. m_insertDataBase = QSqlDatabase::database("conn1");
    5. m_insertDataBase.setDatabaseName("/home/amet/userLog.db");
    6. m_insertDataBase.open();
    7.  
    8. if(m_insertDataBase.isOpen()){
    9.  
    10. qDebug() <<"connected to DB" ;
    11. }
    12. else{
    13. qDebug() <<"error in opening DB";
    14. m_insertDataBase.open();
    15. }
    16.  
    17. qDebug() << "insert Log Message called";
    18. QSqlQuery insertQuery("INSERT INTO userlogevents (firstName, lastName, userName, eventMessage, dateTime) VALUES('John', 'Doe', 'JohnnyD', '"+msg+"', datetime(current_timestamp))", conn1);
    19. insertQuery.exec();
    20. m_insertDataBase.close();
    21. }
    To copy to clipboard, switch view to plain text mode 


    --------Header file with instance of QSqlDatabase object---------
    Qt Code:
    1. private:
    2. QSqlDatabase m_insertDataBase;
    3. };
    To copy to clipboard, switch view to plain text mode 

    I'm running into issues trying to implement an instance of the QSqlDatabase class (to connect to database just once) When I call my query with my database named connection ("conn1") I get 'conn1' was not declared in this scope I need to create an instance of this class (QSqlDatabase) to connect/open database once...? can any one help me get a better understanding of instances and creating a connection to a database with an instance of QSqlDatabase class so you only have to connect to it once or if you need to connect to it agian you just use the instance variable?
    Last edited by jfinn88; 23rd August 2016 at 22:14.

  2. #2
    Join Date
    Mar 2008
    Location
    Kraków, Poland
    Posts
    1,540
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows
    Thanked 284 Times in 279 Posts

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    conn1 is the name of db connection not C++ variable. Variable name is m_insertDataBase - C++ ABC.
    And line 4
    Qt Code:
    1. m_insertDataBase = QSqlDatabase::database("conn1");
    To copy to clipboard, switch view to plain text mode 
    is unnecessary.

  3. #3
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,416
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows
    Thanks
    37
    Thanked 1,544 Times in 1,494 Posts

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    You also don't want to do the addDatabase() and setDatabaseName() calls every time, just once, when "m_insertDataBase" is not valid yet.
    See QSqlDatabase:::isValid().

    Also, as someone had already pointed out in another thread, don't concatenated an input string into a SQL Query, always use prepare() and bound values for proper escaping.

    Cheers,
    _

  4. #4
    jfinn88 Guest

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    Quote Originally Posted by Lesiok View Post
    conn1 is the name of db connection not C++ variable. Variable name is m_insertDataBase - C++ ABC.
    And line 4
    Qt Code:
    1. m_insertDataBase = QSqlDatabase::database("conn1");
    To copy to clipboard, switch view to plain text mode 
    is unnecessary.
    It didn't seem to work when passing the driver and the connection name with the line of code above this one. So I tried setting the connection name again but kept getting "conn1 was not declared in this scope". I know conn1 is the db connection name I declare it in the code above and in this line and I declare the instance variable in my header file. I only used the above code seeing if setting the db connection name would work like this I realize its unnecessary, I was just trying something to get it to work. I'm not sure if I need to declare the instance variable under public or not in the header file?


    Added after 4 minutes:


    Quote Originally Posted by anda_skoa View Post
    You also don't want to do the addDatabase() and setDatabaseName() calls every time, just once, when "m_insertDataBase" is not valid yet.
    See QSqlDatabase:::isValid().

    Also, as someone had already pointed out in another thread, don't concatenated an input string into a SQL Query, always use prepare() and bound values for proper escaping.

    Cheers,
    _
    You are talking about binding my Msg variable correct? the parameter I'm using in my sql statement?

    I was using a prepare statement before but took it out to try to short my code and it only takes one parameter wasn’t sure how to tell if its using the right connection. I will go back to using the prepare statement as suggested to allow proper escaping. How do I set the conn1 connection since The prepare() fcn only takes one argument can't pass it the connection name with sql statement do I just set the connection by

    Qt Code:
    1. m_selectDataBase = QSqlDatabase::database("conn2");
    To copy to clipboard, switch view to plain text mode 

    I will look at documentation on isValid(). How do I only call those methods once when the instance is not valid? little explanation on how this works be great, you got a example?
    Last edited by jfinn88; 24th August 2016 at 16:29.

  5. #5
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,416
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows
    Thanks
    37
    Thanked 1,544 Times in 1,494 Posts

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    Quote Originally Posted by jfinn88 View Post
    You are talking about binding my Msg variable correct? the parameter I'm using in my sql statement?
    Yes

    Quote Originally Posted by jfinn88 View Post
    How do I set the conn1 connection since The prepare() fcn only takes one argument can't pass it the connection name with sql statement
    You pass the QSqlDatabase handle to the QSqlQuery constructor.
    Qt Code:
    1. QSqlQuery insertQuery(m_insertDataBase);
    2. insertQuery.prepare(...);
    To copy to clipboard, switch view to plain text mode 

    Quote Originally Posted by jfinn88 View Post
    I will look at documentation on isValid(). How do I only call those methods once when the instance is not valid? little explanation on how this works be great, you got a example?
    Qt Code:
    1. if (!m_insertDataBase.isValid() {
    2. // addDatabase, setDatabaseName
    3. }
    To copy to clipboard, switch view to plain text mode 

    Cheers,
    _

  6. #6
    jfinn88 Guest

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    I have two classes I need to use an instance variable of the class QSqlDatabase to set database connections. I created an instance variable of the QSqlDatabase class in both classes under private:
    --------------- Header file----------------
    Qt Code:
    1. //Data struct for user event log
    2. struct userEventLogMsg{
    3. //hold all values for a single list entry,
    4. QString id;
    5. QString username;
    6. QString eventmessage;
    7. QString datetime;
    8. };
    9.  
    10. //---Class UserEventDailyLog responsible for XMUI UserEvnetLog | Subed classed: QAbstractTableModel---//
    11. class UserEventLog : public QAbstractListModel
    12. {
    13. Q_OBJECT
    14.  
    15. public:
    16. explicit UserEventLog(QObject *parent = 0);
    17.  
    18. ~UserEventLog();
    19.  
    20. enum userEventRoles {idRole= Qt::UserRole + 220, nameRole, msgRole, dateRole};
    21.  
    22. int rowCount(const QModelIndex & parent) const;
    23.  
    24. QHash<int, QByteArray> roleNames() const;
    25.  
    26. QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const;
    27.  
    28. Q_INVOKABLE void addEvent(const userEventLogMsg &msg);
    29.  
    30. void dbConnect();
    31.