-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeatherCache.cpp
More file actions
102 lines (90 loc) · 2.59 KB
/
Copy pathWeatherCache.cpp
File metadata and controls
102 lines (90 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "WeatherCache.h"
#include <QCoreApplication>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
#include <QDebug>
WeatherCache::WeatherCache(QObject *parent)
: QObject(parent)
{
initDb();
}
WeatherCache::~WeatherCache()
{
if (m_db.isOpen()) m_db.close();
}
void WeatherCache::initDb()
{
m_db = QSqlDatabase::addDatabase("QSQLITE");
// 绿色版:数据库与 exe 同目录,即删即走不留痕迹
QString path = QCoreApplication::applicationDirPath() + "/weather_cache.db";
m_db.setDatabaseName(path);
if (!m_db.open()) {
qWarning() << "WeatherCache: 无法打开数据库" << m_db.lastError().text();
return;
}
QSqlQuery q(m_db);
q.exec("CREATE TABLE IF NOT EXISTS cache ("
" k TEXT PRIMARY KEY,"
" data TEXT,"
" ts INTEGER"
")");
}
QString WeatherCache::get(const QString &key, int ttlSeconds)
{
QSqlQuery q(m_db);
q.prepare("SELECT data, ts FROM cache WHERE k = ?");
q.addBindValue(key);
if (!q.exec() || !q.next()) return {};
qint64 ts = q.value(1).toLongLong();
qint64 now = QDateTime::currentSecsSinceEpoch();
if (now - ts > ttlSeconds) {
// 过期,删掉
QSqlQuery del(m_db);
del.prepare("DELETE FROM cache WHERE k = ?");
del.addBindValue(key);
del.exec();
return {};
}
return q.value(0).toString();
}
void WeatherCache::set(const QString &key, const QString &json)
{
QSqlQuery q(m_db);
q.prepare("INSERT OR REPLACE INTO cache (k, data, ts) VALUES (?, ?, ?)");
q.addBindValue(key);
q.addBindValue(json);
q.addBindValue(QDateTime::currentSecsSinceEpoch());
if (!q.exec())
qWarning() << "WeatherCache: 写入失败" << q.lastError().text();
}
void WeatherCache::cleanExpired(int ttlSeconds)
{
qint64 cutoff = QDateTime::currentSecsSinceEpoch() - ttlSeconds;
QSqlQuery q(m_db);
q.prepare("DELETE FROM cache WHERE ts < ?");
q.addBindValue(cutoff);
q.exec();
}
void WeatherCache::clearAll()
{
QSqlQuery q(m_db);
q.exec("DELETE FROM cache");
}
void WeatherCache::save(const QString &key, const QString &value)
{
QSqlQuery q(m_db);
q.prepare("INSERT OR REPLACE INTO cache (k, data, ts) VALUES (?, ?, ?)");
q.addBindValue(key);
q.addBindValue(value);
q.addBindValue(QDateTime::currentSecsSinceEpoch());
q.exec();
}
QString WeatherCache::load(const QString &key)
{
QSqlQuery q(m_db);
q.prepare("SELECT data FROM cache WHERE k = ?");
q.addBindValue(key);
if (!q.exec() || !q.next()) return {};
return q.value(0).toString();
}