Search code examples
qtsqlanywhere

QDateTime insertion and retrival in SQLAnywhere Database


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.


Solution

  • 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