Use SQLite in Qt

Project file (.pro)

Add the following line to your .pro file

QT += sql

Header

#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>

class DatabaseManager
{
    public:
        DatabaseManager();
        ~DatabaseManager();

    public:
        bool openDB();
        bool deleteDB();
        QSqlError lastError();

    private:
        QSqlDatabase db;
};

Source

bool DatabaseManager::openDB()
{
    // Find QSLite driver
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("database_name_here");

    // Open databasee
    return db.open();
}

QSqlError DatabaseManager::lastError()
{
    // If opening database has failed user can ask
    // error description by QSqlError::text()
    return db.lastError();
}

bool DatabaseManager::deleteDB()
{
    // Close database
    db.close();
    return QFile::remove("database_name_here");
}

Execute a query

QSqlQuery query;
// Create a new table
query.exec("CREATE TABLE filelist(fullpath VARCHAR PRIMARY KEY, timestamp VARCHAR)");

// Prepare file Information to insert
QFileInfo currentFile = ...;
QString filepath = currentFile.absoluteFilePath();
QString timestamp = currentFile.lastModified().date().toString("yyyy-MM");

// Insert a record to the database
query.exec("INSERT INTO filelist VALUES('" + filepath + "', '" + timestamp  + "')");

// You can also insert a record as following
query.prepare("INSERT INTO filelist VALUES(?, ?)");
query.addBindValue(filepath);
query.addBindValue(timestamp);
query.exec();

query.exec("DROP TABLE filelist");
Contact Us
  • SenseTime Research, Shenzhen Bay Eco-Technology Park
  • cshzxie [at] gmail [dot] com