XML连接MySQL
时间: 2023-11-24 21:51:33 浏览: 73
以下是使用Qt中的QXmlStreamReader和QSqlDatabase连接MySQL的XML文件的示例代码:
```cpp
#include <QCoreApplication>
#include <QXmlStreamReader>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 读取XML文件
QFile file("../plane/MysqlXml.xml");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Failed to open file."; return -1;
}
QXmlStreamReader xmlReader(&file);
// 解析XML文件
QString hostName, databaseName, userName, password;
int port = 0;
while (!xmlReader.atEnd()) {
if (xmlReader.isStartElement()) {
if (xmlReader.name() == "hostName") {
hostName = xmlReader.readElementText();
} else if (xmlReader.name() == "port") {
port = xmlReader.readElementText().toInt();
} else if (xmlReader.name() == "datebase") {
databaseName = xmlReader.readElementText();
} else if (xmlReader.name() == "username") {
userName = xmlReader.readElementText();
} else if (xmlReader.name() == "passWord") {
password = xmlReader.readElementText();
}
}
xmlReader.readNext();
}
// 连接MySQL数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(hostName);
db.setPort(port);
db.setDatabaseName(databaseName);
db.setUserName(userName);
db.setPassword(password);
if (!db.open()) {
qDebug() << "Failed to connect to database:" << db.lastError().text();
return -1;
}
// 执行SQL语句
QSqlQuery query;
if (!query.exec("SELECT * FROM table_name")) {
qDebug() << "Failed to execute SQL query:" << query.lastError().text();
return -1;
}
while (query.next()) {
// 处理查询结果
}
return a.exec();
}
```
阅读全文