Qt的SQL操做,DELETE,SELECT

#include <QObject>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QString>
 
class DatabaseManager : public QObject
    {
    public:
        DatabaseManager(QObject *parent = 0);
        ~DatabaseManager();
 
    public:
        bool openDB();
        bool deletePerson(int id);
 
    private:
        QSqlDatabase db;
    };

Delete a person from the database:sql

bool DatabaseManager::deletePerson(int id)
    {
    bool ret = false;
    if (db.isOpen())
        {
        QSqlQuery query;
        ret = query.exec(QString("delete from person where id=%1").arg(id));
        }
    return ret;
    }

The rest of the code:app

bool DatabaseManager::openDB()
    {
    // Find QSLite driver
    db = QSqlDatabase::addDatabase("QSQLITE");
 
    #ifdef Q_OS_LINUX
    // NOTE: We have to store database file into user home folder in Linux
    QString path(QDir::home().path());
    path.append(QDir::separator()).append("my.db.sqlite");
    path = QDir::toNativeSeparators(path);
    db.setDatabaseName(path);
    #else
    // NOTE: File exists in the application private folder, in Symbian Qt implementation
    db.setDatabaseName("my.db.sqlite");
    #endif
 
    // Open databasee
    return db.open();
    }

以上參考http://developer.nokia.com/community/wiki/Deleting_data_from_a_database_in_Qtspa

SELECT核心語句rest

bool DatabaseManager::getPerson(int id, PersonData*& person)
    {
    bool ret = false;
 
    QSqlQuery query(QString("select * from person where id = %1").arg(id));
    if (query.next())
        {
        person->id = query.value(0).toInt();
        person->firstname = query.value(1).toString();
        person->lastname = query.value(2).toString();
        person->age = query.value(3).toInt();
        ret = true;
        }
 
    return ret;
    }

以上參考http://developer.nokia.com/community/wiki/Searching_for_data_in_a_database_in_Qtcode

 

若是有多個參數,能夠是 %1,%2,%3 以後.arg().arg().arg()括號裏填對應變量。sqlite

相關文章
相關標籤/搜索