db_bridge/mysql_db.cpp
changeset 12 9f0ce4eaa1ce
child 14 862d63715611
new file mode 100644
--- /dev/null
+++ b/db_bridge/mysql_db.cpp
@@ -0,0 +1,69 @@
+/**
+ * db_bridge/mysql_db.cpp
+ * Copyright 2008 (C) Markus Broeker
+ */
+
+#include <mysql_db.h>
+
+MySQL_DB::MySQL_DB (std::string srv, std::string usr, std::string pwd, std::string db)
+{
+    server = srv;
+    user = usr;
+    password = pwd;
+    database = db;
+    conn = mysql_init (NULL);
+}
+
+MySQL_DB::~MySQL_DB ()
+{
+    if (conn != NULL) {
+        mysql_close (conn);
+        std::cerr << "Datenbank wird geschlossen" << std::endl;
+    }
+}
+
+bool MySQL_DB::connect ()
+{
+    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;
+}
+
+std::vector < std::vector<std::string> >MySQL_DB::query (std::string sql_string)
+{
+    std::vector <std::string> vec;
+    std::vector < std::vector <std::string> >rows;
+    MYSQL_ROW row;
+    int i;
+
+    /*
+     * 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 ();
+    }
+
+    if (res != NULL) {
+        mysql_free_result (res);
+    }
+
+    return rows;
+}