db_bridge/postgresql_db.cpp
changeset 12 9f0ce4eaa1ce
child 14 862d63715611
new file mode 100644
--- /dev/null
+++ b/db_bridge/postgresql_db.cpp
@@ -0,0 +1,73 @@
+/**
+ * db_bridge/postgresql_db.cpp
+ * Copyright 2008 (C) Markus Broeker
+ */
+
+#include <postgresql_db.h>
+
+PostgreSQL_DB::PostgreSQL_DB (std::string srv, std::string usr, std::string pwd, std::string db)
+{
+    server = (srv != "") ? "host=" + srv : "";
+    user = (usr != "") ? "user=" + usr : "user=" + std::string (getenv ("USER"));
+    password = (pwd != "") ? "password=" + pwd : "";
+    database = "dbname=" + db;
+
+    if (server != "" && pwd == "") {
+        std::cerr << "HBA funktioniert nur mit Passwoertern..." << std::endl;
+    }
+
+    conninfo = server + " " + user + " " + password + " " + database;
+}
+
+PostgreSQL_DB::~PostgreSQL_DB ()
+{
+    if (conn != NULL) {
+        PQfinish (conn);
+        std::cerr << "Datenbank wird geschlossen" << std::endl;
+    }
+}
+
+bool PostgreSQL_DB::connect ()
+{
+    if ((conn = PQconnectdb (conninfo.c_str ())) == NULL) {
+        std::cerr << server << ": " << "ERROR " << std::endl;
+        return false;
+    }
+
+    std::cerr << "Verbindungsparameter: " << conninfo << std::endl;
+    return true;
+}
+
+std::vector < std::vector<std::string> >PostgreSQL_DB::query (std::string sql_string)
+{
+    std::vector <std::string> vec;
+    std::vector < std::vector <std::string> >rows;
+    PGresult *res;
+    int i, j, nFields;
+
+    /*
+     * send SQL query
+     */
+    res = PQexec (conn, sql_string.c_str ());
+
+    nFields = PQnfields (res);
+
+    std::cout << "Die Abfrage ergab " << nFields << " Zeilen." << std::endl;
+
+    /*
+     * push everything into a vector< vector<string> >
+     */
+    for (i = 0; i < PQntuples (res); i++) {
+        for (j = 0; j < nFields; j++) {
+            vec.push_back (PQgetvalue (res, i, j));
+        }
+        rows.push_back (vec);
+        vec.clear ();
+    }
+
+    if (res != NULL) {
+        PQclear (res);
+    }
+
+    return rows;
+}