db_bridge/postgresql_db.cpp
author Markus Bröker <mbroeker@largo.dyndns.tv>
Sun, 26 Jul 2009 18:14:15 +0200
changeset 102 b8ff193b1a01
parent 65 76514757b0d6
child 125 9c0fdc119939
permissions -rw-r--r--
Property java.library.path i've found out how to set the library path correctly with java tools committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * db_bridge/postgresql_db.cpp
 * Copyright 2008 (C) Markus Broeker
 */

#include <cstdlib>
#include <postgresql_db.hpp>
#include <exception>
#include <console.hpp>

PostgreSQL_DB::PostgreSQL_DB (std::string srv, std::string usr, std::string pwd, std::string db)
{
    server = srv;
    user = (usr != "") ? usr : getenv ("USER");
    password = pwd;
    database = db;

    conninfo = "user=" + user + " dbname=" + database;

    if (server != "" && pwd == "") {
        std::cout << "Passwort von " << user << "@" << server << ": ";
        Console::getpass (password);
        conninfo += " host=" + server + " password=" + password;
    }
}

PostgreSQL_DB::~PostgreSQL_DB ()
{
    if (conn != NULL) {
        PQfinish (conn);
        std::cerr << "Datenbank wird geschlossen" << std::endl;
    }
}

bool PostgreSQL_DB::connect ()
{
    std::cerr << "Verbindungsparameter:" << " host=" << ((server != "") ? server : "LOCAL")
        << " user=" << user << " password=" << password << " database=" << database << std::endl;

    if ((conn = PQconnectdb (conninfo.c_str ())) == NULL) {
        std::cerr << server << ": " << "ERROR " << std::endl;
        return false;
    }

    return true;
}

Abstract_DB::DB_RESULT PostgreSQL_DB::query (std::string sql_string)
{
    Abstract_DB::DB_ROW vec;
    Abstract_DB::DB_RESULT rows;
    PGresult *res;
    int i, j;
    int nFields, nRows;

    /*
     * send SQL query
     */
    res = PQexec (conn, sql_string.c_str ());

    nFields = PQnfields (res);
    nRows = PQntuples (res);

    std::cout << "Die Abfrage hat " << nFields << " Spalte(n) und " << nRows << " Reihe(n)." << std::endl;

    /*
     * push everything into a vector< vector<string> >
     */
    for (i = 0; i < nRows; 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;
}