#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:
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:
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_Qt
SELECT核心语句
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_Qt
如果有多个参数,可以是 %1,%2,%3 之后.arg().arg().arg()括号里填对应变量。
时间: 2024-11-10 19:10:49