一步步学Qt.第二天-续集-mysql连接成功

不断辛苦,不断尝试,这把才将mysql的驱动ok了.

写了一个小小的demo

#include <QApplication>
#include <QtSql/QSqlDatabase>
#include <QtSql>
#include <QDebug>
#include <QMessageBox>

int main(int argc,char *argv[]){
    QApplication app(argc,argv);

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setDatabaseName("test");
    db.setUserName("root");
    db.setPassword("admin");
    bool succ = db.open();
    if (succ) {
        qDebug("yes");
    } else {
        qDebug("No");
        QMessageBox::critical(0,QObject::tr("Error"),db.lastError().text());
    }

    return app.exec();
}


在写这个程序的时候,忘记了之前在linux中写连接mysql的时候遇到过的问题.

就出现了如下的错误:

debug/main.o: In function `Z5qMainiPPc':

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:9: undefined reference to `_imp___ZN12QSqlDatabase17defaultConnectionE'

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:9: undefined reference to `_imp___ZN12QSqlDatabase11addDatabaseERK7QStringS2_'

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:9: undefined reference to `_imp___ZN12QSqlDatabaseD1Ev'

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:10: undefined reference to `_imp___ZN12QSqlDatabase15setDatabaseNameERK7QString'

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:11: undefined reference to `_imp___ZN12QSqlDatabase11setUserNameERK7QString'

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:12: undefined reference to `_imp___ZN12QSqlDatabase11setPasswordERK7QString'

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:13: undefined reference to `_imp___ZN12QSqlDatabase4openEv'

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:21: undefined reference to `_imp___ZN12QSqlDatabaseD1Ev'

E:\WorkPlace\Qt\dbdemo-build-desktop/../dbdemo/main.cpp:21: undefined reference to `_imp___ZN12QSqlDatabaseD1Ev'

collect2: ld returned 1 exit status

后来在http://topic.csdn.net/u/20101108/20/0ea01860-f4ce-482a-9784-3c726ca61ff5.html 找到了解决办法,谢谢这位朋友.

就是在.pro文件中加入:

QT += sql

再有我在使用

QMessageBox::critical(0,QObject::tr("Error"),db.lastError().text());
的时候,db.lastError()后面的.text()函数,在没有#include <Qtsql>的时候,没有自动提示.我的感觉和认识是没有自动提示,那么很有可能是错误的.但是加入这个之后.就可以了,不过,这头文件,只是所谓的头文件,那是一个目录?

有哪位朋友知道的,还请赐教.小弟感激!

---------------------------------------------

在完成上面的工作之后,

To use the SDK and QtCreator directly, copy these libraries to your C:\Qt\...\qt\plugins\sqldrivers\, and copyC:\MySQL\MySQL51\lib\opt\libmysql.dll to your C:\Qt\...\qt\bin\.

程序运行结果:

Starting E:\WorkPlace\Qt\dbdemo-build-desktop\debug\dbdemo.exe...

yes



oh yeah...今天的任务完成....准备睡觉


posted @ 2011-08-26 01:38  Podevor  阅读(632)  评论(0编辑  收藏  举报