forked from bskari/mysql-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMySql.cpp
108 lines (89 loc) · 2.32 KB
/
MySql.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 "MySql.hpp"
#include "MySqlException.hpp"
#include <cassert>
#include <cstdint>
#include <mysql/mysql.h>
#include <string>
#include <sstream>
#include <vector>
using std::string;
using std::vector;
MySql::MySql(
const char* hostname,
const char* username,
const char* password,
const uint16_t port
)
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)
: MySql(hostname, username, password, nullptr, port)
{
}
#else
: connection_(mysql_init(nullptr))
{
if (nullptr == connection_) {
throw MySqlException("Unable to connect to MySQL");
}
const MYSQL* const success = mysql_real_connect(
connection_,
hostname,
username,
password,
nullptr,
port,
nullptr,
0);
if (nullptr == success) {
MySqlException mse(connection_);
mysql_close(connection_);
throw mse;
}
}
#endif
MySql::MySql(
const char* const hostname,
const char* const username,
const char* const password,
const char* const database,
const uint16_t port
)
: connection_(mysql_init(nullptr))
{
if (nullptr == connection_) {
throw MySqlException("Unable to connect to MySQL");
}
const MYSQL* const success = mysql_real_connect(
connection_,
hostname,
username,
password,
database,
port,
nullptr,
0);
if (nullptr == success) {
MySqlException mse(connection_);
mysql_close(connection_);
throw mse;
}
}
MySql::~MySql() {
mysql_close(connection_);
}
my_ulonglong MySql::runCommand(const char* const command) {
if (0 != mysql_real_query(connection_, command, strlen(command))) {
throw MySqlException(connection_);
}
// If the user ran a SELECT statement or something else, at least warn them
const my_ulonglong affectedRows = mysql_affected_rows(connection_);
if ((my_ulonglong) - 1 == affectedRows) {
// Clean up after the query
MYSQL_RES* const result = mysql_store_result(connection_);
mysql_free_result(result);
throw MySqlException("Tried to run query with runCommand");
}
return affectedRows;
}
MySqlPreparedStatement MySql::prepareStatement(const char* const command) const {
return MySqlPreparedStatement(command, connection_);
}