forked from bskari/mysql-cpp
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySql.cpp
More file actions
Latest commit
108 lines (89 loc) · 2.32 KB
/
Copy pathMySql.cpp
File metadata and controls
108 lines (89 loc) · 2.32 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
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(
constchar* hostname,
constchar* username,
constchar* password,
constuint16_t port
)
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)
: MySql(hostname, username, password, nullptr, port)
{
}
#else
: connection_(mysql_init(nullptr))
{
if (nullptr == connection_) {
throwMySqlException("Unable to connect to MySQL");
}
constMYSQL* 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(
constchar* const hostname,
constchar* const username,
constchar* const password,
constchar* const database,
constuint16_t port
)
: connection_(mysql_init(nullptr))
{
if (nullptr == connection_) {
throwMySqlException("Unable to connect to MySQL");
}
constMYSQL* 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(constchar* const command) {
if (0 != mysql_real_query(connection_, command, strlen(command))) {
throwMySqlException(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);
throwMySqlException("Tried to run query with runCommand");
}
return affectedRows;
}
MySqlPreparedStatement MySql::prepareStatement(constchar* const command) const {
returnMySqlPreparedStatement(command, connection_);
}