请帮我用qt c++写多线程调用数据库定时保存数据的代码
时间: 2024-05-09 07:16:49 浏览: 95
Qt5 C++ 多线程工业气体标定 1)使用OPC 封装COM 2)C++调用OPC; 3)使用经典界面; 4)使用QT专业皮肤
好的,我可以为您提供代码示例。以下是使用Qt C++编写多线程调用数据库定时保存数据的代码:
```
#include <QThread>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
class DatabaseSaver : public QObject
{
Q_OBJECT
public:
DatabaseSaver() {};
public slots:
void saveData()
{
// 连接到数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("mydatabase");
db.setUserName("myusername");
db.setPassword("mypassword");
if (!db.open()) {
qWarning() << "DatabaseSaver: Failed to connect to database:" << db.lastError().text();
return;
} else {
qDebug() << "DatabaseSaver: Connected to database successfully!";
}
// 查询要保存的数据
QSqlQuery query("SELECT * FROM mytable WHERE timestamp > NOW() - INTERVAL 1 DAY");
// 将数据保存到文件
QFile file("mydata.csv");
if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) {
qWarning() << "DatabaseSaver: Failed to open file for writing:" << file.errorString();
return;
}
QTextStream out(&file);
while (query.next()) {
QString data;
for (int i = 0; i < query.record().count(); i++) {
data += query.value(i).toString() + ",";
}
data.chop(1); // 删除最后一个逗号
out << data << "\n";
}
// 关闭文件和数据库连接
file.close();
db.close();
qDebug() << "DatabaseSaver: Data saved successfully!";
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 在后台线程中定期保存数据
DatabaseSaver *saver = new DatabaseSaver();
QThread *thread = new QThread();
saver->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), saver, SLOT(saveData()));
QObject::connect(saver, SIGNAL(finished()), thread, SLOT(quit()));
QObject::connect(saver, SIGNAL(finished()), saver, SLOT(deleteLater()));
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
return a.exec();
}
#include "main.moc"
```
请注意,这只是一个示例,您需要根据自己的需求来修改代码。如果您需要更多帮助,请随时让我知道。
阅读全文