-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMySQLite.cpp
91 lines (79 loc) · 2.26 KB
/
MySQLite.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
#include "MySQLite.h"
#include "QMessageBox"
#include <QObject>
MySQLite::MySQLite(const QString &dbpath, const QString &connName)
: m_connName(connName)
{
db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", connName));
db->setDatabaseName(dbpath);
if (!db->open())
{
QMessageBox::warning(NULL, QObject::tr("数据库错误"),
QObject::tr("无法打开数据库: %1")
.arg(db->lastError().text()));
}
}
MySQLite::~MySQLite()
{
qDebug() << "当前的连接是:" << db->connectionName()
<<" ,它将要被移除!";
db->close();
delete db;
db = NULL;
QSqlDatabase::removeDatabase(m_connName);
QStringList connect = QSqlDatabase::connectionNames();
for(int i=0;i<connect.size();i++)
{
qDebug() << "移除后还包括这些连接" << connect.at(i);
}
qDebug() << "已经移出了一个连接";
}
QVariant MySQLite::rexec(const QString &sql)
{
QSqlQuery query = db->exec(sql);
if (query.next())
{
return query.record().value(0);
}
else
{
if (query.lastError().number() != -1) // 没有对应的数据
{
QMessageBox::warning(NULL,QObject::tr("数据库错误"),
QObject::tr("没有对应的数据: %1 %2")
.arg(query.lastError().number()).arg(query.lastError().type()));
}
}
return "";
}
uint MySQLite::lastInsertID()
{
return rexec("SELECT last_insert_rowid();").toUInt();
}
bool MySQLite::exec(const QString &sql)
{
db->exec(sql);
QSqlError::ErrorType type = db->lastError().type();
if (type != QSqlError::NoError)
{
QString message = db->lastError().text();
QMessageBox::warning(NULL,QObject::tr("数据库错误"),
QObject::tr("数据库错误: %1").arg(message));
return false;
}
return true;
}
bool MySQLite::isTableExist(const QString &tableName)
{
return db->tables(QSql::Tables).contains(tableName);
}
int MySQLite::recordCount(const QString &tableName)
{
if(isTableExist(tableName))
{
QSqlQuery query(QString("select count(*) from %1").arg(tableName), *db);
query.next();
return query.value(0).toInt();
}
return 0;
}