//***************************************************************************************
// C++ Read data from Mysql database 
//***************************************************************************************
#include <iostream>
#include <mariadb/conncpp.hpp>           //Database Driver

int main() {
    try {
        sql::Driver     *driver;
        sql::Connection *conn;
        sql::Statement  *stmt;
        sql::ResultSet  *res;

        const std::string conn_str = "tcp://localhost/demo2";       //conn_string host:port/dbname 
        const std::string user     = "demo2";                       //username
        const std::string pswd     = "demo2";                       //password

        driver = sql::mariadb::get_driver_instance();               //access DB driver

        conn = driver->connect(conn_str, user, pswd);               //connect to DB

        stmt = conn->createStatement();                             //create a statement

        std::string sql = "SELECT * FROM addrbook " \
                          "ORDER BY 1 ";

        res = stmt->executeQuery(sql);                              //execute SQL get cursor

        std::cout << "LNAME \t FNAME \t PHONE \t\t ADDRESS"         //print column headers
                  << std::endl;

        while (res->next())                                         //iterate thru the cursor rows
        {
            std::string lname  = res->getString(1).c_str();         //or use getString("lastname")
            std::string fname  = res->getString(2).c_str();         //use getInt() for numeric
            std::string addr   = res->getString(3).c_str();
            std::string city   = res->getString(4).c_str();
            std::string state  = res->getString(5).c_str();
            std::string zip    = res->getString(6).c_str();
            std::string phone  = res->getString(7).c_str();
            
            std::cout << lname << "\t" << fname << "\t"                       
                      << phone << "\t" << addr                 
                      << std::endl;
        }

        delete res;                                                 //release resources
        delete stmt;
        delete conn;
    } 
    catch (sql::SQLException &e) {
        std::cerr << "#ERROR: SQLException in " << __FILE__;
        std::cerr << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl;
        std::cerr << "#ERROR: " << e.what() << std::endl;
        std::cerr << "(MySQL error code: " << e.getErrorCode() << ",";
        std::cerr << " SQLState: " << e.getSQLState() << ")" << std::endl;
    }

    return EXIT_SUCCESS;
}