db_bridge/mysql_db.cpp
author Markus Bröker <mbroeker@largo.dyndns.tv>
Tue, 09 Mar 2010 12:58:27 +0100
changeset 122 50ba3b0e271a
parent 65 76514757b0d6
child 126 52722ac7693f
permissions -rw-r--r--
GNU Make and GNU Indent The Makefile depends on GNU tools and the user may choose the location committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * 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;

    /*
     * 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);

    /*
     * push everything into a vector< vector<string> >
     */
    while ((row = mysql_fetch_row (res)) != NULL) {
        i = 0;
        while (row[i] != NULL) {
            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;
}