-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmysql_writer.cpp
64 lines (55 loc) · 1.58 KB
/
mysql_writer.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
#include "mysql_writer.h"
#include <mysql.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sstream> // for ostringstream
#include <stdio.h>
MysqlWriter::MysqlWriter(config_t cfg)
{
this->cfg = cfg;
}
MysqlWriter::~MysqlWriter()
{
mysql_close(this->conn);
}
void MysqlWriter::connect()
{
const char *server;
const char *user;
const char *password;
const char *database;
if(!config_lookup_string(&this->cfg, "db.host", &server)) {
throw "MySQL host is not defined";
}
if(!config_lookup_string(&this->cfg, "db.username", &user)) {
throw "MySQL username is not defined";
}
if(!config_lookup_string(&this->cfg, "db.password", &password)) {
throw "MySQL password is not defined";
}
if(!config_lookup_string(&this->cfg, "db.database", &database)) {
throw "MySQL database is not defined";
}
this->conn = mysql_init(NULL);
if (!mysql_real_connect(this->conn, server,
user, password, database, 0, NULL, 0)) {
throw mysql_error(this->conn);
}
time_t rawtime;
struct tm *timeinfo;
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(this->numeric_table_name, sizeof(this->numeric_table_name), "archive_numeric_%Y_%m", timeinfo);
}
void MysqlWriter::saveNumericValue(double value, int dataSourceId)
{
std::ostringstream q;
q << "INSERT INTO " << this->numeric_table_name << " (date, source_id, value) VALUES(NOW(), " << dataSourceId << ", " << value << ")";
//std::cout << q.str() << '\n';
std::string tmp1 = q.str();
const char* tmp2 = tmp1.c_str();
if (mysql_query(this->conn, tmp2)) {
throw mysql_error(this->conn);
}
}