Results 1 to 20 of 61

Thread: using an isntance of QSqlDatabase for connection defiinition

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #6
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    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.  
    32. void sqlSelect();
    33.  
    34. private:
    35. QList<userEventLogMsg> m_userEventList;
    36. QSqlDatabase m_selectDataBase;
    37. };
    To copy to clipboard, switch view to plain text mode 

    Qt Code:
    1. //---------CPP file--------------//
    2. //
    3. // UserEventLogModel
    4. //
    5.  
    6. //---Constructor---//
    7. UserEventLog::UserEventLog(QObject *parent):QAbstractListModel(parent) {
    8.  
    9. }
    10. //---Destructor---//
    11. UserEventLog::~UserEventLog() {
    12.  
    13. }
    14.  
    15. int UserEventLog::rowCount(const QModelIndex &parent) const {
    16. Q_UNUSED(parent);
    17. qDebug()<< m_userEventList.count();
    18. return m_userEventList.count();
    19. }
    20.  
    21. QHash<int, QByteArray> UserEventLog::roleNames() const {
    22. QHash<int, QByteArray> roleNames;
    23. roleNames.insert(idRole, "id");
    24. roleNames.insert(nameRole, "userName");
    25. roleNames.insert(msgRole, "eventMessage");
    26. roleNames.insert(dateRole, "dateTime");
    27. qDebug()<< roleNames;
    28. return roleNames;
    29. }
    30.  
    31. QVariant UserEventLog::data(const QModelIndex &index, int role) const {
    32. if (index.row() < 0 || index.row() >= m_userEventList.count()){
    33. return QVariant();
    34. }
    35.  
    36. QVariant text;
    37.  
    38. if(role == idRole) {
    39. userEventLogMsg msg = m_userEventList.at(index.row());
    40. text = msg.id;
    41. qDebug() << text;
    42. }
    43. else if(role == nameRole) {
    44. userEventLogMsg msg = m_userEventList.at(index.row());
    45. text = msg.username;
    46. qDebug() << text;
    47. }
    48. else if(role == msgRole) {
    49. userEventLogMsg msg = m_userEventList.at(index.row());
    50. text = msg.eventmessage;
    51. qDebug() << text;
    52. }
    53. if(role == dateRole) {
    54. userEventLogMsg msg = m_userEventList.at(index.row());
    55. text = msg.datetime;
    56. qDebug() << text;
    57. }
    58. return text;
    59. }
    60.  
    61. void UserEventLog::addEvent(const userEventLogMsg &msg) {
    62.  
    63. beginInsertRows(QModelIndex(), 0, 0);
    64. m_userEventList.insert(0, msg);
    65. endInsertRows();
    66. }
    67.  
    68. void UserEventLog::dbConnect() {
    69. m_selectDataBase = QSqlDatabase::addDatabase("QSQLITE", "conn2");
    70. qDebug() << m_selectDataBase.isValid();
    71. m_selectDataBase.setDatabaseName("/home/amet/userLog.db");
    72. m_selectDataBase.open();
    73.  
    74. if(!m_selectDataBase.open()){
    75. qDebug() <<"error in opening DB";
    76. }
    77. else{
    78. qDebug() <<"connected to DB" ;
    79. }
    80. }
    81. void UserEventLog::sqlSelect() {
    82.  
    83. //m_selectDataBase = QSqlDatabase::database("conn2");
    84. qDebug() << m_selectDataBase.isValid();
    85. m_selectDataBase.open();
    86. QSqlQuery selectQuery;
    87. selectQuery.prepare("SELECT id, userName, eventMessage, dateTime FROM userlogevents");
    88. qDebug() <<selectQuery.lastError();
    89.  
    90. if(selectQuery.exec()){
    91. qDebug()<<"sql statement exicuted fine";
    92. }
    93. else{
    94. qDebug() <<"Errors accured with sql statement";
    95. qDebug() <<selectQuery.lastError();
    96. }
    97.  
    98. while (selectQuery.next()){
    99. userEventLogMsg msg;
    100. UserEventLog model;
    101. msg.id = selectQuery.value(0).toString();
    102. msg.username = selectQuery.value(1).toString();
    103. msg.eventmessage = selectQuery.value(2).toString();
    104. msg.datetime = selectQuery.value(3).toString();
    105. model.addEvent(msg);
    106. }
    107. //m_selectDataBase.close();
    108. //m_selectDataBase.removeDatabase("conn2");
    109. }
    110. //----------------------------------------------------------------//
    To copy to clipboard, switch view to plain text mode 

    my other class that need a database connection to the same database

    ---------CPP file-----------
    Qt Code:
    1. void XMUI::hdpiWindow()
    2. {
    3. mUserEventLogModel = new UserEventLog();
    4. mUserEventLogModel->dbConnect();
    5. mUserEventLogModel->sqlSelect();
    6. m_QmlEngine->rootContext()->setContextProperty("UserEventLog", mUserEventLogModel);
    7. }
    8.  
    9. void XMUI::insertLogMessage(QString msg)
    10. {
    11. m_insertDataBase = QSqlDatabase::addDatabase("QSQLITE", "conn1");
    12. m_insertDataBase.setDatabaseName("/home/amet/userLog.db");
    13. m_insertDataBase.open();
    14.  
    15. if(m_insertDataBase.isOpen()){
    16.  
    17. qDebug() <<"connected to DB" ;
    18. }
    19. else{
    20. qDebug() <<"error in opening DB";
    21. m_insertDataBase.open();
    22. }
    23.  
    24. qDebug() << "insert Log Message called";
    25. QSqlQuery insertQuery(m_insertDataBase);
    26. insertQuery.prepare("INSERT INTO userlogevents (firstName, lastName, userName, eventMessage, dateTime) VALUES('John', 'Doe', 'JohnnyD', ':eventMessage', datetime(current_timestamp))");
    27. insertQuery.bindValue(":eventMessage", msg);
    28. insertQuery.exec();
    29. //m_insertDataBase.close();
    30. //m_insertDataBase.removeDatabase("conn1");
    31. }
    To copy to clipboard, switch view to plain text mode 


    ----header file--------
    Qt Code:
    1. class XMUI : public QObject
    2. {
    3. Q_OBJECT
    4.  
    5. public:
    6. explicit XMUI(QQuickWidget* _quickWidget);
    7.  
    8. void hdpiWindow();
    9.  
    10. Q_INVOKABLE void insertLogMessage(QString msg);
    11.  
    12. private:
    13. QSqlDatabase m_insertDataBase;
    To copy to clipboard, switch view to plain text mode 


    Added after 18 minutes:


    Quote Originally Posted by anda_skoa View Post
    Yes


    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 
    I was passing the name of my connection not the instance variable, changed it to instance variable.

    Qt Code:
    1. if (!m_insertDataBase.isValid() {
    2. // addDatabase, setDatabaseName
    3. }
    To copy to clipboard, switch view to plain text mode 

    Cheers,
    _
    I moved the add and set methods inside an if condition to set them if the database is not valid. However I get confused because I need to connect to the database to begin with... If I'm only setting them when it not valid how do I initially set the connect the first time. set it in the constructor?

    Qt Code:
    1. void XMUI::insertLogMessage(QString msg)
    2. {
    3. //qDebug() << m_insertDataBase.connectionNames();
    4.  
    5. if(!m_insertDataBase.isValid()){
    6. qDebug() <<"error in opening DB";
    7. m_insertDataBase = QSqlDatabase::addDatabase("QSQLITE", "conn1");
    8. m_insertDataBase.setDatabaseName("/home/amet/userLog.db");
    9. qDebug() << m_insertDataBase.connectionNames();
    10. }
    11. else{
    12. qDebug() <<"connected to DB";
    13. m_insertDataBase.open();
    14. //qDebug() << m_insertDataBase.lastError();
    15. }
    16.  
    17. m_insertDataBase.open();
    18. QSqlQuery m_insertQuery(m_insertDataBase);
    19. m_insertQuery.prepare("INSERT INTO userlogevents (firstName, lastName, userName, eventMessage, dateTime) VALUES('John', 'Doe', 'JohnnyD', ':eventMessage', datetime(current_timestamp))");
    20. m_insertQuery.bindValue(":eventMessage", msg);
    21. m_insertQuery.exec();
    22. qDebug() << m_insertQuery.lastError();
    23. //m_insertDataBase.close();
    24. //QSqlDatabase::removeDatabase("conn1");
    25. }
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 24th August 2016 at 21:38.

Similar Threads

  1. Replies: 16
    Last Post: 4th September 2013, 00:49
  2. How to set x509 on a QSqlDatabase Connection?
    By m3rlin in forum Qt Programming
    Replies: 24
    Last Post: 21st February 2012, 04:04
  3. Windows OCI QSqlDatabase connection
    By hollyberry in forum Newbie
    Replies: 10
    Last Post: 13th February 2012, 22:13
  4. QSqlDatabase Connection Close on Destruction
    By Sanuden in forum Qt Programming
    Replies: 1
    Last Post: 1st September 2011, 15:32
  5. QSqlDatabase connection timeout?
    By joseprl89 in forum Qt Programming
    Replies: 6
    Last Post: 27th March 2011, 01:43

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.