CellModules
Connection.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <iostream>
4#include <sstream>
5#include <stdexcept>
6#if __has_include(<libpq-fe.h>)
7# include <libpq-fe.h>
8#else
9# include <postgresql/libpq-fe.h>
10#endif
11
12namespace PluginSQL {
14 PGconn* conn = nullptr;
15
16 public:
17 Connection(std::string user, std::string pass, std::string host, int port, std::string dbname) {
18 int libpq_ver = PQlibVersion();
19 //std::cout << "Version of libpq: " << libpq_ver << std::endl;
20
21 std::stringstream ss;
22 ss << "user=" << user << " password=" << pass << " host=" << host << " dbname=" << dbname << " port=" << port;
23
24 conn = PQconnectdb(ss.str().c_str());
25
26 if(PQstatus(conn) != CONNECTION_OK)
27 throw std::runtime_error(PQerrorMessage(conn));
28
29 //std::cout << "Server version: " << PQserverVersion(conn) << std::endl;
30 //std::cout << "User: " << PQuser(conn)<< std::endl;
31 //std::cout << "Database name: " << PQdb(conn) << std::endl;
32 }
33
35 if(conn != nullptr)
36 PQfinish(conn);
37 conn = nullptr;
38 }
39
40 void Execute(std::string query){
41 // same for insert, update, delete, begin, commit ...
42 PGresult* res = PQexec(conn, query.c_str());
43
44 if(PQresultStatus(res) != PGRES_COMMAND_OK)
45 throw std::runtime_error(PQerrorMessage(conn));
46 }
47
48
49};
50}
Connection(std::string user, std::string pass, std::string host, int port, std::string dbname)
Definition: Connection.hpp:17
void Execute(std::string query)
Definition: Connection.hpp:40