头文件:
#include <qsqlquery.h> #include <qsqldatabase.h>
(注:需要先适配数据库)
函数定义:
public:bool verifyLogin(const QString& account, const QString& password);QString getUserName(const QString& account);QString getUserHeadPixmap(const QString& account);private:bool connectMySQL();private:QSqlDatabase base;
源代码:
连接:
bool UseMySQL::connectMySQL() {if(DEBUG) qDebug() << QSqlDatabase::drivers();//开始连接数据库base = QSqlDatabase::addDatabase(DB_DRIVER, DB_CONN_NAME);base.setDatabaseName(DB_NAME);base.setHostName(DB_HOST_NAME);base.setUserName(DB_ACCOUNT);base.setPassword(DB_PASSWORD);base.setPort(DB_PORT);if(!base.open()) return false;return true; }
使用:
bool UseMySQL::verifyLogin(const QString & account, const QString & password) {//构造时就会执行一次QSqlQuery sql(QString("SELECT code FROM accounts WHERE ID = %1").arg(account),base);if (sql.next()) {QString result = sql.value(0).toString();if (result == password) {return true;}}return false;}
QString UseMySQL::getUserName(const QString & account) {QSqlQuery sql(QString("SELECT Name FROM tab WHERE ID = %1").arg(account), base);if (sql.next()) {QString result = sql.value(0).toString();return result;}return QString(); }
QString UseMySQL::getUserHeadPixmap(const QString & account) {QSqlQuery sql(QString("SELECT picture FROM tab WHERE ID = %1").arg(account), base);if (sql.next()) {QString result = sql.value(0).toString();return result;}return QString(); }