#include <iostream>
#include <vector>
#include <mysql++/query.h>
#include <mysql++/result.h>

using namespace std;
const char * db_name  = "mysql_cpp_data";
const char * host     = "localhost";
const char * username = "root";
const char * password = "passwd";

struct stock {
   int item;
   int num;
   float weight;
   int price;
   string sdate;    
};
int main(int argc, char *argv[])
{
#if 1
   try {                        
       // Establish the connection to the database server.
       mysqlpp::Connection con(mysqlpp::use_exceptions);
       if (!con.connect(db_name, host, username, password)) {
           return 1;
       }

       mysqlpp::Query query = con.query();
       query << "select * from stock";

       cout << "Query: " << query.preview() << endl;

       mysqlpp::Result rest = query.store();
       mysqlpp::Result::iterator i = rest.begin();
       mysqlpp::Row row = *i;

       cout << "Result:" << endl;
       for (int j = 0; j < row.size(); j++) {
           cout << rest.field_name(j);
           cout << setw(20);
       }
       cout << endl;

       for (i = rest.begin(); i != rest.end(); i++) {
           cout << setw(0);
           row = *i;
           for (int j = 0; j < row.size(); j++) {
               cout << row.at(j);
               cout << setw(20);
           }
           cout << endl;
       }

       query << "insert into stock(num, weight, price, sdate)\
            values(8 ,98, 132, '2005-5-10 12:12:12')";
       query.execute();
   }

   catch (const mysqlpp::BadQuery& er) {
       // Handle any query errors
       cerr << "Query error: " << er.what() << endl;
       return -1;
   }
   catch (const mysqlpp::BadConversion& er) {
       // Handle bad conversions; e.g. type mismatch populating 'stock'
       cerr << "Conversion error: " << er.what() << endl <<
               "\tretrieved data size: " << er.retrieved <<
               ", actual size: " << er.actual_size << endl;
       return -1;
   }
   catch (const mysqlpp::Exception& er) {
       // Catch-all for any other MySQL++ exceptions
       cerr << "Error: " << er.what() << endl;
       return -1;
   }
#endif

   return 0;
}