db_bridge/mysql_db.cpp
author Markus Bröker <mbroeker@largo.dyndns.tv>
Sat, 13 Dec 2008 17:58:16 +0100
changeset 23 7acfc5eda7ed
parent 22 0db9235d68d9
child 40 be3f5582b839
permissions -rw-r--r--
this seems to be the proper way under ms, but it won't work under wine committer: Markus Bröker <mbroeker@largo.homelinux.org>

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

#include <mysql_db.h>
#include <console.h>

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;
}