-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDB.cpp
More file actions
89 lines (78 loc) · 2.22 KB
/
DB.cpp
File metadata and controls
89 lines (78 loc) · 2.22 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
//
// Created by cmg on 5/30/20.
//
#include "DB.h"
DB::DB() {
mysql = mysql_init(nullptr);
if (mysql == nullptr) {
cout << "error occurs " << mysql_error(mysql);
exit(1);
}
}
DB::~DB() {
if (mysql != nullptr) {
mysql_close(mysql);
}
}
bool DB::connectDb() {
if (!mysql_real_connect(mysql, host, user, password, db, 0, nullptr, 0)) {
cout << "error occurs " << mysql_error(mysql);
exit(1);
} else {
// cout<<"Mysql Database Connected"<<endl;
return true;
}
}
bool DB::execSql(string sql,string& res) {
if (mysql_query(mysql, sql.c_str())) {
cout << "query error " << mysql_error(mysql) << endl;
return false;
} else {
result = mysql_use_result(mysql);
if (result) {
unsigned int num_fields = mysql_num_fields(result);
unsigned int num_rows = mysql_num_rows(reinterpret_cast<MYSQL_RES *>(mysql));
for (int i = 0; i < num_rows; i++) {
row = mysql_fetch_row(result);
if (!row) break;
for (int j = 0; j < num_fields; j++) {
// cout << row[j] << "\t";
res += row[j];
res += "\t";
}
// cout << endl;
res += "\n";
}
}
mysql_free_result(result);
}
return true;
}
bool DB::execSql(string sql) {
if (mysql_query(mysql, sql.c_str())) {
cout << "query error " << mysql_error(mysql) << endl;
return false;
} else {
result = mysql_use_result(mysql);
if (result) {
unsigned int num_fields = mysql_num_fields(result);
unsigned int num_rows = mysql_num_rows(reinterpret_cast<MYSQL_RES *>(mysql));
for (int i = 0; i < num_rows; i++) {
row = mysql_fetch_row(result);
if (!row) break;
for (int j = 0; j < num_fields; j++) {
cout << row[j] << "\t";
}
cout << endl;
}
}
mysql_free_result(result);
}
return true;
}
bool DB::closeDb() {
if (mysql != nullptr) {
mysql_close(mysql);
}
return true;
}