Qt5.12 创建一个连接ORACLE11数据库的应用,通过执行4条SQL语句,并将查询结果导出csv文件到指定目录,每1小时执行一次SQL语句并导出
时间: 2024-12-16 15:31:07 浏览: 13
在Qt5.12中,你可以使用QSqlDatabase模块来连接Oracle 11数据库,QFileWriter来写入CSV文件,然后结合QTimer设置定时任务。以下是一个基本的示例代码:
```cpp
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QFileWriter>
#include <QTimer>
class OracleApp : public QObject
{
Q_OBJECT
private slots:
void connectAndExport() {
QSqlDatabase db = QSqlDatabase::addDatabase("QOracle");
db.setHostName("hostname");
db.setPort("port");
db.setDatabaseName("service_name");
db.setUserName("username");
db.setPassword("password");
if (!db.open()) {
qCritical() << "Failed to open the database: " << db.lastError().text();
return;
}
for (int i = 1; i <= 4; ++i) {
QSqlQuery query(db);
query.prepare("SELECT * FROM table" + QString::number(i));
if (!query.exec()) {
qCritical() << "Failed to execute query " << i << ": " << query.lastError().text();
continue;
}
QFile csvFile("results/" + QString::number(i) + ".csv");
csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
QTextStream out(&csvFile);
out << "Column1, Column2, ... \n"; // Write column headers
while (query.next()) {
QStringList row;
row << query.value(0).toString() << ...; // Replace with your columns
out << row.join(",") << "\n";
}
csvFile.close();
}
// Schedule a new execution every hour
QTimer::singleShot(3600000, this, SLOT(connectAndExport()));
}
public:
explicit OracleApp(QObject *parent = nullptr) : QObject(parent) {}
};
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
OracleApp oracleApp;
oracleApp.connectAndExport();
return app.exec();
}
```
在这个示例中,我们首先建立一个QSqlDatabase实例,然后执行四个SQL查询并将结果写入CSV文件。接着,我们使用QTimer在1小时后再次触发`connectAndExport`函数。
阅读全文