《qt连接数据库(MySQL).docx》由会员分享,可在线阅读,更多相关《qt连接数据库(MySQL).docx(2页珍藏版)》请在优知文库上搜索。
1、代码0CH/Objc以ivcC代码QSqIDatabascdb=QSqgabaSe:addDalabase(QMYSQWQODBCr/);becomes(henewdefaultconnectiondbsertJscrNamcCmoCW用户名db.sctP於SWOrd(pa*swM?系Wdb.seHostNameClocalhost*);db.setDatabaseNane(esi故据库名db.selConncctOptk)ns(C1.IENT_SS1.=I:C1.IENT_IGNORE_SPACE=*)PSS1.db.s以PM33O6)ft-Iif(db.open()(qDebug(),oe
2、nn,clsc(qDcbug()wopcnfailed;实例:Winulude#inc)u(lc连接函数bclCruHeConneCI沁n()QSqIDatabascdb=QSq11)atabasc:addI)atabasc(QMYSQ1.);db.se(HostName(,localhosl,tXdb.setDaiabaseNamelest*):db.sctUscrNamc(root*);db.setPasswordC,123456w);if(!db.open()(QMessageBox:xrilical(O.QObject:tr(DalabaseError),db.lastErrort).
3、tcxt();returnfalse:I假如连接胜利,执行杳询QSqIQueryquery:query.excxselectfromstu:QStringmajor=query.valuc(1).toS(ring(;QMessagcBox:cri(ical(0.nanw.major);Jreturntrue;I”主函数intmain(intargc.char4*argv)Q/Xpplicalionap(argc.argv);i(!crealeConnection()rctumI;returnapp.exec():实例2求Qt的mysql驱动IibqsqImysq1.arqsqlmysql.dl
4、lWincludeWincludc#includcboolCooneciDatabaseOQSIDatabaseconn=QSqlDatabasc:addDatabasc(QMYSQ1.);conn.se(HostName(localhosi,conn.setUserName(,roo,):conn.selPassword(1123456h);conn.scDatabscNamc(lest);if(!conn.open()QMeSSageBox:CriIiC叫OQ1.abd:IrUtf8(“数据库连接失败),conn.lastE11r().tcxt();returnfalse;Ireturntrue;intmain(intargc.char*argv)QApplicalionapp(ar*c.argv);i1(!connectI)atabasc()return1;returna.exec():