首页 > 代码库 > Qt的SQL操作,DELETE,SELECT
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:
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()括号里填对应变量。
Qt的SQL操作,DELETE,SELECT
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。