db_bridge/mysql_db.cpp
changeset 12 9f0ce4eaa1ce
child 14 862d63715611
equal deleted inserted replaced
11:0a8be4eac87e 12:9f0ce4eaa1ce
       
     1 /**
       
     2  * db_bridge/mysql_db.cpp
       
     3  * Copyright 2008 (C) Markus Broeker
       
     4  */
       
     5 
       
     6 #include <mysql_db.h>
       
     7 
       
     8 MySQL_DB::MySQL_DB (std::string srv, std::string usr, std::string pwd, std::string db)
       
     9 {
       
    10     server = srv;
       
    11     user = usr;
       
    12     password = pwd;
       
    13     database = db;
       
    14     conn = mysql_init (NULL);
       
    15 }
       
    16 
       
    17 MySQL_DB::~MySQL_DB ()
       
    18 {
       
    19     if (conn != NULL) {
       
    20         mysql_close (conn);
       
    21         std::cerr << "Datenbank wird geschlossen" << std::endl;
       
    22     }
       
    23 }
       
    24 
       
    25 bool MySQL_DB::connect ()
       
    26 {
       
    27     if (!mysql_real_connect (conn, server.c_str (), user.c_str (), password.c_str (), database.c_str (), 0, NULL, 0)) {
       
    28         std::cerr << server << ": " << mysql_error (conn) << std::endl;
       
    29         return false;
       
    30     }
       
    31 
       
    32     return true;
       
    33 }
       
    34 
       
    35 std::vector < std::vector<std::string> >MySQL_DB::query (std::string sql_string)
       
    36 {
       
    37     std::vector <std::string> vec;
       
    38     std::vector < std::vector <std::string> >rows;
       
    39     MYSQL_ROW row;
       
    40     int i;
       
    41 
       
    42     /*
       
    43      * send SQL query
       
    44      */
       
    45     if (mysql_query (conn, sql_string.c_str ())) {
       
    46         std::cerr << server << ": " << mysql_error (conn) << std::endl;
       
    47         return rows;
       
    48     }
       
    49 
       
    50     res = mysql_use_result (conn);
       
    51 
       
    52     /*
       
    53      * push everything into a vector< vector<string> >
       
    54      */
       
    55     while ((row = mysql_fetch_row (res)) != NULL) {
       
    56         i = 0;
       
    57         while (row[i] != NULL) {
       
    58             vec.push_back (row[i++]);
       
    59         }
       
    60         rows.push_back (vec);
       
    61         vec.clear ();
       
    62     }
       
    63 
       
    64     if (res != NULL) {
       
    65         mysql_free_result (res);
       
    66     }
       
    67 
       
    68     return rows;
       
    69 }