#include <QtGui>
//连接函数
bool createConnection(){
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("test");
db.setUserName("root");
db.setPassword("123456");
if(!db.open()){
QMessageBox::critical(0, QObject::tr("Database Error"),
db.lastError().text());
return false;
}
//如果连接成功,执行查询
QSqlQuery query;
query.exec("select * from student");
while (query.next()) {
QString name = query.value(3).toString();
QString major = query.value(1).toString();
QMessageBox::critical(0,name,major);
}
return true;
}
//主函数
int main(int argc,char** argv){
QApplication app(argc, argv);
if (!createConnection()){
return 1;
}
return app.exec();
}