db_bridge/mysql_db.cpp
author Markus Bröker <mbroeker@volpe.spectre.org>
Wed, 18 Aug 2010 16:15:18 +0200
changeset 141 0b5befeb361e
parent 126 52722ac7693f
permissions -rw-r--r--
getbits: calculates the proper value but showed a different one

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

#include <cstdlib>
#include <mysql_db.hpp>
#include <console.hpp>

MySQL_DB::MySQL_DB (std::string srv, std::string usr, std::string pwd, std::string db)
{
    server = (srv != "") ? srv : "localhost";
    user = (usr != "") ? usr : getenv ("USER");
    password = pwd;
    database = db;
    conn = mysql_init (NULL);

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

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

bool MySQL_DB::connect ()
{
    std::cerr << "Verbindungsparameter:" << " host=" << server
        << " user=" << user << " password=" << password << " database=" << database << std::endl;

    if (!mysql_real_connect (conn, server.c_str (), user.c_str (), password.c_str (), database.c_str (), 0, NULL, 0)) {
        std::cerr << server << ": " << mysql_error (conn) << std::endl;
        return false;
    }

    return true;
}

Abstract_DB::DB_RESULT MySQL_DB::query (std::string sql_string)
{
    Abstract_DB::DB_ROW vec;
    Abstract_DB::DB_RESULT rows;
    MYSQL_ROW row;
    int i = 0, num_fields = 0;

    /*
     * send SQL query
     */
    if (mysql_query (conn, sql_string.c_str ())) {
        std::cerr << server << ": " << mysql_error (conn) << std::endl;
        return rows;
    }

    res = mysql_use_result (conn);
    num_fields = mysql_num_fields (res);

    /*
     * push everything into a vector< vector<string> >
     */
    while ((row = mysql_fetch_row (res)) != NULL) {
	for (i = 0; i < num_fields; i++) {
            vec.push_back (row[i]);
        }
        rows.push_back (vec);
        vec.clear ();
    }

    std::cerr << "Die Abfrage hat " << i << " Spalte(n) und " << rows.size () << " Reihe(n)." << std::endl;

    if (res != NULL) {
        mysql_free_result (res);
    }

    return rows;
}