ubuntu Qt环境链接mysql测试

qt链接mysql数据库的测试

#include "Mysql.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QCoreApplication>

Mysql::Mysql()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");//加载数据库驱动
    db.setHostName("127.0.0.1");//链接本地数据库
    db.setUserName("root");//访问数数据库的用户名
    db.setPassword("1");//密码
    db.setDatabaseName("student");//数据库名
    db.open();//打开数据库,简单测试,未作错误检测,以下如此
    QSqlQuery query;
    query.exec("insert into stu values('tsong','123')");
    query.exec("insert into stu values('tfeng','456')");
}
int main(int argc,char **argv)
{
    QCoreApplication a(argc,argv);
    Mysql sql;
    return a.exec();
}

注:其中
db.setDatabaseName("student");//数据库名
加载数据库名,可以使用绝对路径,和相对路径;使用绝对路径一般不会出错.
但是,当我们使用相对路径的时候,就比比较容易出错,关键是这个相对路径是
相对于谁,对于qt来说,是项目的编译结果目录[debug或者release的目录],而不是我们创建的工程
/*判断登陆是输入密码和用户名是否正确*/
bool UserHandle::whetherMatch(QString username, QString passwd)
{
    DbManager *instance = DbManager::getInstance();
    instance->createConnection();
    QSqlQuery query;
    query.prepare("select * from tb_user where username = :username " //此处切记:username[此处有空格]"
                  "and passwd = :passwd;");
    query.bindValue(":username", username);
    query.bindValue(":passwd", passwd);
    query.exec();
    while(query.next())
    {
       QString qName = query.value(1).toString();
       QString qPasswd = query.value(2).toString();
       if(qName == username && qPasswd == passwd)
       {
           instance->removeConnection();
           return true;
       }
    }
    instance->removeConnection();
    return false;
}

你可能感兴趣的:(数据库,mysql,ubuntu,测试,qt)