#ifndef DBUTIL_H
#define DBUTIL_H
#include <QString>
#include <QtSql>
class DBUtil {
private:
DBUtil();
public:
static QSqlDatabase getDatabase(bool *ok = 0, QString *error = 0);
static void removeDatabase();
static const QString DATABASE_NAME;
static const QString DATABASE_CONNECT_NAME;
};
#endif // DBUTIL_H
#include "DBUtil.h"
const QString DBUtil::DATABASE_NAME("/Users/Biao/Documents/Workspace/QtWorkspace/Laundry/Database.db");
const QString DBUtil::DATABASE_CONNECT_NAME("LaundryDatabase");
DBUtil::DBUtil() {
}
QSqlDatabase DBUtil::getDatabase(bool *ok, QString *error) {
QSqlDatabase db;
if (!QSqlDatabase::contains(DBUtil::DATABASE_CONNECT_NAME)) {
db = QSqlDatabase::addDatabase("QSQLITE", DBUtil::DATABASE_CONNECT_NAME);
db.setDatabaseName(DBUtil::DATABASE_NAME);
} else {
db = QSqlDatabase::database(DBUtil::DATABASE_CONNECT_NAME, true);
}
if (!db.isOpen()) {
bool result = db.open();
if (0 != ok) {
*ok = result;
}
if ((false == result) && (0 != error)) {
*error = db.lastError().text();
}
}
return db;
}
void DBUtil::removeDatabase() {
QSqlDatabase::removeDatabase(DBUtil::DATABASE_CONNECT_NAME);
}
void DAOAdmin::update(bool *ok, QString *error) const {
// Update the admin into the database.
QSqlDatabase db = DBUtil::getDatabase(ok, error);
QSqlQuery query(db);
QString sql("UPDATE admin SET password=:password, permission=:permission, title=:title, creator_name=:creator_name ");
sql += "WHERE name=:name";
query.prepare(sql);
query.bindValue(":password", password);
query.bindValue(":permission", permission);
query.bindValue(":title", title);
query.bindValue(":creator_name", creatorName);
query.bindValue(":name", name);
bool result = query.exec();
// Set the error information.
if (0 != ok) {
*ok = result;
}
if ((false == result) && (0 != error)) {
*error = query.lastError().text();
}
}