Qt的SQL操作,DELETE,SELECT

#include <QObject>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QString> class DatabaseManager : public QObject
{
public:
DatabaseManager(QObject *parent = );
~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().toInt();
person->firstname = query.value().toString();
person->lastname = query.value().toString();
person->age = query.value().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()括号里填对应变量。

上一篇:PAT 解题报告 1003. Emergency (25)


下一篇:H3 BPM总部乔迁 开启新篇章 筑梦新征程