Guest User

Untitled

a guest
Sep 18th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. // mainwindows.h
  2.  
  3. public:
  4. QSqlDatabase mydb;
  5. void connClose()
  6. {
  7. connected = false;
  8. mydb.close();
  9. mydb.QSqlDatabase();
  10. mydb.removeDatabase(QSqlDatabase::defaultConnection);
  11. }
  12.  
  13. bool connOpen()
  14. {
  15. if( !connected )
  16. {
  17. mydb = QSqlDatabase::addDatabase("QODBC"); //uses dsn, connects fine.
  18. mydb.setDatabaseName("Test");
  19. if(!mydb.open())
  20. {
  21. qDebug() << mydb.lastError().text();
  22. connected = false;
  23. }
  24. else
  25. {
  26. qDebug()<<"Connected";
  27. connected = true;
  28. }
  29. }
  30. return connected;
  31. }
  32.  
  33. private:
  34. static bool connected;
  35.  
  36. Financelog::Financelog(QWidget *parent) :
  37. QDialog(parent),
  38. ui(new Ui::Financelog)
  39. {
  40. ui->setupUi(this);
  41. setWindowFlags( windowFlags() | Qt::WindowMinimizeButtonHint |
  42. Qt::WindowContextHelpButtonHint | Qt::WindowMinMaxButtonsHint );
  43.  
  44. MainWindow conn; // call the connection string
  45. if(!conn.connOpen())
  46. ui->label_sec_status->setText("<font color='red'>Failed to Open Database</font>");
  47. else
  48. ui->label_sec_status->setText("<font color='green'>Connected</font>");
  49.  
  50. QSqlQueryModel * modal=new QSqlQueryModel();
  51.  
  52. conn.connOpen(); // ---- **DO I NEED THIS? REMOVING STOPS CRASHES.**
  53.  
  54. QSqlQuery* qry=new QSqlQuery(conn.mydb);
  55.  
  56. qry->prepare("select DEAL_DATE, DEAL_NUMB, CCICOMM, CCIPREM, INCOME from LOG");
  57. qry->exec();
  58. modal->setQuery(*qry);
  59. ui->tableView->setModel(modal);
  60. ui->tableView->resizeColumnsToContents();
  61. ui->tableView->setAlternatingRowColors(true);
  62. ui->tableView->setStyleSheet("alternate-background-color: #009900; background-color: #006600;");
  63.  
  64. //delete qry; **DO I NEED THIS TO RELEASE MEMORY?**
  65.  
  66. conn.connClose(); // **DO I NEED THIS?**
  67.  
  68. qDebug() << (modal->rowCount());
  69. }
  70.  
  71. //only once, i.e. in your windows constructor
  72. conn.connOpen();
  73.  
  74. //set up the model
  75. QSqlQueryModel * modal=new QSqlQueryModel();
  76.  
  77. QSqlQuery qry(conn.mydb);
  78.  
  79. qry.prepare("...");
  80. qry.exec();
  81. modal->setQuery(qry);
  82. //...
  83.  
  84. // do not delete the query or close the database connection!
  85.  
  86. qDebug() << (modal->rowCount());
  87.  
  88. model->deleteLater();
  89. conn.connClose();
Add Comment
Please, Sign In to add comment