1

I'm trying to store and access Date and Time in a Table which is SQLAnywhere16 Database.

Which Data type should be used in Qt so that it can be used for all my Qt business Logic and UI. I'm thinking to use QDateTime, so what are the Function which will help to insert the datetime in Query and convert back to datetime from Query result.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Raj G Y
  • 13
  • 3

1 Answers1

0

Yes, QDateTime is very compatible with QtSql, very easy to work with. Here is some code for insertion and selection:

// SELECT
QSqlQuery querySelect;
if (!querySelect.exec("SELECT datetime FROM author"))
{
    //handle error        
}
while (querySelect.next()) 
{
    QDateTime dateTime = querySelect.value(0).toDateTime();
    doSomething(dateTime);
}

// INSERT
QSqlQuery queryInsert;
if (!queryInsert.prepare("INSERT INTO author (datetime) VALUES (:dateTime)"))
{
    //handle error
}
QDateTime dateTime = QDateTime::currentDateTime();
queryInsert.bindValue(":dateTime", dateTime);

if (!queryInsert.exec())
{
    //handle error        
}

Be sure that the SQL column is of type DATETIME or TIMESTAMP, so that the value can be converted correctly.

Read more about Data Types for Qt-supported Database Systems here: https://doc.qt.io/qt-5/sql-types.html

Rick Pat
  • 789
  • 5
  • 14
  • Thanks for your answer! For Insertion Prepared query used here, is it not possible with normal query? – Raj G Y Mar 08 '19 at 01:53
  • I think you need to format the datetime to a valid string then. This should work: `queryInsert.exec("INSERT INTO author (datetime) VALUES (" + dateTime.toString("yyyy-dd-MM hh:mm:ss.z") + ")");` – Rick Pat Mar 08 '19 at 12:10
  • But i think prepared statements make the code more readable, besides preventing sql-injections. – Rick Pat Mar 08 '19 at 12:12