Qt5.7连接Mysql数据库:
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("imgdb");
db.setPort(3306);
db.setUserName("root");
db.setPassword("123456");
bool ok = db.open();
if(!ok){
qDebug()<<"Unable to open database";
}else{
qDebug()<<"Database connection established";
QSqlQuery myquery("select * from imgdb",db);
while(myquery.next())
{
QString imgClass = myquery.value(0).toString().trimmed();
qDebug()<<imgClass;
}
}
db.close();
db.setHostName("localhost");
db.setDatabaseName("imgdb");
db.setPort(3306);
db.setUserName("root");
db.setPassword("123456");
bool ok = db.open();
if(!ok){
qDebug()<<"Unable to open database";
}else{
qDebug()<<"Database connection established";
QSqlQuery myquery("select * from imgdb",db);
while(myquery.next())
{
QString imgClass = myquery.value(0).toString().trimmed();
qDebug()<<imgClass;
}
}
db.close();
在编译程序时,发现无法加载QMYSQL驱动。
出现如下的出错信息:
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QPSQL QPSQL7
Unable to open database