#include #include #include #include void preparedSimple(QSqlDatabase& db) { qDebug() << "PREPARED QUERY SIMPLE:"; qDebug() << "----------------------"; QSqlQuery query(db); const QString queryString = QStringLiteral(R"(SELECT timestamp FROM table_with_timestamp WHERE id = ? ORDER BY timestamp DESC)"); query.prepare(queryString); query.addBindValue(QStringLiteral("DATE1")); // Expected results: // "2022-05-07 12:52:58" bool ok = query.exec(); if (!ok) { qDebug() << query.lastError(); return; } if (query.next()) { int colIx{ 0 }; QVariant vvv = query.value(colIx); int metaType = vvv.typeId(); QDateTime timestamp = query.value(colIx++).toDateTime(); qint64 msecEpoch = timestamp.toMSecsSinceEpoch(); const QString timestampString = timestamp.toString(Qt::ISODate); qDebug() << "msecEpoch:" << msecEpoch; qDebug() << "timestampString:" << timestampString; qDebug() << ""; } } void simple(QSqlDatabase& db) { qDebug() << "NON-PREPARED QUERY SIMPLE:"; qDebug() << "--------------------------"; QSqlQuery query(db); const QString queryString = QStringLiteral(R"(SELECT timestamp FROM table_with_timestamp WHERE id = "DATE1" ORDER BY timestamp DESC)"); // Expected results: // "2022-05-07 12:52:58" bool ok = query.exec(queryString); if (!ok) { qDebug() << query.lastError(); return; } if (query.next()) { int colIx{ 0 }; QVariant vvv = query.value(colIx); int metaType = vvv.typeId(); QDateTime timestamp = query.value(colIx++).toDateTime(); qint64 msecEpoch = timestamp.toMSecsSinceEpoch(); const QString timestampString = timestamp.toString(Qt::ISODate); qDebug() << "msecEpoch:" << msecEpoch; qDebug() << "timestampString:" << timestampString; qDebug() << ""; } } int main(int argc, char* argv[]) { QCoreApplication a(argc, argv); qDebug() << "Running Qt Version: " << qVersion(); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setDatabaseName("testdb"); db.setUserName("testuser"); db.setPassword("testuser"); if (!db.open()) { qDebug() << db.lastError(); return 1; } qDebug() << "SQL Driver: " << db.driverName(); qDebug() << ""; QSqlQuery q(db); q.exec("DROP TABLE IF EXISTS table_with_timestamp;"); q.exec("CREATE TABLE table_with_timestamp (timestamp datetime NOT NULL, id varchar(255) NOT NULL, PRIMARY KEY(id));"); q.exec("INSERT INTO table_with_timestamp (timestamp, id) VALUES (\"2022-05-07 12:52:58\",\"DATE1\");"); q.exec("INSERT INTO table_with_timestamp (timestamp, id) VALUES (\"2023-05-07 00:00:00\",\"DATE2\");"); preparedSimple(db); simple(db); db.close(); //return a.exec(); }