您好,欢迎访问三七文档
当前位置:首页 > IT计算机/网络 > 数据结构与算法 > qt连接数据库(MySQL)
[代码][C/C++/Objective-C]代码QSqlDatabasedb=QSqlDatabase::addDatabase(QMYSQL/*QODBC*/);//becomesthenewdefaultconnectiondb.setUserName(root);//用户名db.setPassword(password);//密码db.setHostName(localhost);db.setDatabaseName(test);//数据库名db.setConnectOptions(CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1);//使用SSLdb.setPort(3306);//端口if(db.open()){qDebug()open\ndb.lastError().driverText()\n;}else{qDebug()openfaile\n;}实例:#includeQtSql#includeQtGui//连接函数boolcreateConnection(){QSqlDatabasedb=QSqlDatabase::addDatabase(QMYSQL);db.setHostName(localhost);db.setDatabaseName(test);db.setUserName(root);db.setPassword(123456);if(!db.open()){QMessageBox::critical(0,QObject::tr(DatabaseError),db.lastError().text());returnfalse;}//如果连接成功,执行查询QSqlQueryquery;query.exec(select*fromstudent);while(query.next()){QStringname=query.value(3).toString();QStringmajor=query.value(1).toString();QMessageBox::critical(0,name,major);}returntrue;}//主函数intmain(intargc,char**argv){QApplicationapp(argc,argv);if(!createConnection()){return1;}returnapp.exec();}实例-2求Qt的mysql驱动libqsqlmysql.a,qsqlmysql.dll#includeQtCore#includeQtGui#includeQtSqlboolconnectDatabase(){QSqlDatabaseconn=QSqlDatabase::addDatabase(QMYSQL);conn.setHostName(localhost);conn.setUserName(root);conn.setPassword(123456);conn.setDatabaseName(test);if(!conn.open()){QMessageBox::critical(0,QLabel::trUtf8(数据库连接失败),conn.lastError().text());returnfalse;}returntrue;}intmain(intargc,char**argv){QApplicationapp(argc,argv);if(!connectDatabase())return1;returnapp.exec();}
本文标题:qt连接数据库(MySQL)
链接地址:https://www.777doc.com/doc-7032876 .html