QT 连接多个数据库,必须指定不同的连接名字

/* QT 连接多个数据库,必须指定不同的连接名字 */ #include "q2.h" #include #include #include QSqlDatabase *db; QSqlDatabase *db2; q2::q2(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) { ui.setupUi(this); db = new QSqlDatabase(QSqlDatabase::addDatabase("QMYSQL")); // 没指定连接名字,则为默认库 db->setDatabaseName("sns"); db->setHostName("127.0.0.1"); db->setPort(3306); db->setUserName("root"); db->setPassword(""); if (! db->open()) { QSqlError e = db->lastError(); qFatal("ServerDB db1: Failed initialization: %s",qPrintable(e.text())); } db2 = new QSqlDatabase(QSqlDatabase::addDatabase("QMYSQL", "db2")); // 如果要连接多个数据库,必须指定不同的连接名字,否则会覆盖上面的默认连接 db2->setDatabaseName("bbs"); db2->setHostName("127.0.0.1"); db2->setPort(3306); db2->setUserName("root"); db2->setPassword(""); if (! db2->open()) { QSqlError e = db2->lastError(); qFatal("ServerDB db1 : Failed initialization: %s",qPrintable(e.text())); } } void q2::on_pushButton_clicked() { if (db->isValid()) { QSqlQuery query; // 查默认库,即 db if (query.prepare("select * from users")) { if (query.exec()) { if (query.next()) ui.pushButton->setText(query.value(2).toString()); else qWarning("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); } else { qWarning("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); } } else { qWarning("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); } } else { qWarning("SQL rejected: Database is gone"); } } void q2::on_pushButton_2_clicked() { if (db2->isValid()) { QSqlQuery query(*db2); // 查另一个数据库 db2 if (query.prepare("select * from users")) { if (query.exec()) { if (query.next()) ui.pushButton_2->setText(query.value(2).toString()); else qWarning("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); } else { qWarning("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); } } else { qWarning("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); } } else { qWarning("SQL rejected: Database is gone"); } } q2::~q2() { db->close(); delete db; db = NULL; db2->close(); delete db2; db2 = NULL; }

你可能感兴趣的:(C/C++,QT)