-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysqlite3.cpp
108 lines (94 loc) · 2.96 KB
/
mysqlite3.cpp
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
103
104
105
106
107
108
#include "mysqlite3.h"
#include<QMutexLocker>
#include<QSqlQuery>
#include<QSqlError>
#include<QCoreApplication>
//init static variable
MySqlite3* MySqlite3::instance = nullptr;
QMutex* MySqlite3::mtxGetInstance = new QMutex();
MySqlite3::MySqlite3()
{
db = QSqlDatabase::addDatabase("QSQLITE");
// 1. 请不要调用QDir::setCurrent()函数,会导致整个程序的相对路径都会更改!!!!!!
// 2. 请将数据库文件放在程序的根目录下,否则会出现找不到数据库文件的错误
db.setDatabaseName("sqlite3/savedFilesInfo.db");
if(!db.open()){
qDebug()<<"in MySqlite3::MySqlite3()";
qDebug() << db.lastError().text();
}
}
MySqlite3::~MySqlite3()
{
db.close();
}
MySqlite3 *MySqlite3::getInstance()
{
//可以使用std::once_flag优化
QMutexLocker locker(mtxGetInstance);
if(instance == nullptr)
instance = new MySqlite3();
return instance;
}
bool MySqlite3::insert(QString hash, QString path)
{
QMutexLocker locker(&mtxSql);
QSqlQuery query(db);
QString order = QString("insert into filesInfo values('%1','%2');").arg(hash,path);
if(!query.exec(order)){
qDebug()<<query.lastError().text();
return false;
}
//qDebug()<<"insert success,order = "<<order;
return true;
}
bool MySqlite3::deleteByHash(QString hash)
{
QMutexLocker locker(&mtxSql);
QSqlQuery query(db);
QString order = QString("delete from filesInfo where fileHash = '%1';").arg(hash);
if(!query.exec(order)){
qDebug()<<query.lastError().text();
return false;
}
//qDebug()<<"delete success,order = "<<order;
return true;
}
QString MySqlite3::getPathByHash(QString hash)
{
QMutexLocker locker(&mtxSql);
//没有找到就返回空字符串
QSqlQuery query(db);
QString order = QString("select path from filesInfo where fileHash = '%1';").arg(hash);
//qDebug()<<order;
if(!query.exec(order)){
qDebug()<<query.lastError().text();
return QString();
}
if(!query.next())
return QString();
return query.value(0).toString();
}
QPair<QString, QString> MySqlite3::getHashAndPathByIndex(int index)
{
QMutexLocker locker(&mtxSql);
QSqlQuery query(db);
QString order = QString("select * from filesInfo;");
if(!query.exec(order)){
qDebug()<<query.lastError().text();
return QPair<QString,QString>();
}
query.seek(index);
return QPair<QString,QString>(query.value(0).toString(),query.value(1).toString());
}
bool MySqlite3::updateByHash(QString hash, QString path)
{
//更新hash对应的值为path,如果不存在则插入一条新的记录
QString p = getPathByHash(hash);
QMutexLocker locker(&mtxSql);
QSqlQuery query(db);
if(p.isEmpty()){
return query.exec(QString("insert into filesInfo values('%1','%2');").arg(hash,path));
}else{
return query.exec(QString("update filesInfo set path = '%1' where fileHash = '%2';").arg(path,hash));
}
}