#include<QtGui>
#include<QtCore>
#include<QtSql>
int main(int argc,char* argv[]){
QApplication app(argc,argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("test");
db.setUserName("root");
db.setPassword("12345678");
if(!db.open()){
QMessageBox::warning(0,QObject::tr("无法打开数据库!"),db.lastError().text());
qDebug()<<QObject::tr("DB Connection Fail!");
return -1;
}
QSqlQuery query;
bool bSuccess=query.exec("select * from mytable;");
if(bSuccess){
while(query.next()){
qDebug()<<query.value(0).toString()<<query.value(1).toInt()<<endl;
}
qDebug()<<QObject::tr("查询成功!");
QMessageBox box;
box.setWindowTitle(QObject::tr("提示"));
box.setIcon(QMessageBox::Information);
box.setText("连接Mysql成功!");
box.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
box.show();
// QMessageBox::about(0,QObject::tr("提示"),QObject::tr("连接Mysql成功!"));
}else
qDebug()<<QObject::tr("连接Mysql失败!");
return 0;
}
Fedora下QT4.8连接MySQL
最新推荐文章于 2025-11-24 20:48:20 发布
本文介绍了一个使用Qt框架连接MySQL数据库并进行查询操作的示例程序。该程序通过QtSql模块实现了与本地MySQL数据库的连接,并从名为mytable的数据表中获取了所有记录。
1万+

被折叠的 条评论
为什么被折叠?



