// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
#include <cstdio>
#include <cstdlib>

#include <iostream>
#include <string>
#include <map>

using namespace std;

#include "mysql.h"

int main()
{
    MYSQL *handle= mysql_init(NULL);
    if(handle == NULL)
    {
        cerr << "MySQL error: " << mysql_error(handle) << endl;
        exit(1);
    }
    if(!mysql_real_connect(handle, "localhost", "root", "", "Test", 0, NULL, 0))
    {
        cerr << "MySQL error: " << mysql_error(handle) << endl;
        exit(1);
    }
    mysql_query(handle, "SELECT * FROM t1");
    MYSQL_RES *result = mysql_store_result(handle);
    int nfields = mysql_num_fields(result);
    /* */
    map<string,int> name2index;
    for(int i=0; i<nfields; i++) {
       name2index[(mysql_fetch_field_direct(result, i))->name] = i;
    }
    /* */
    MYSQL_ROW row;
    char *buf = new char[256];
    while ((row = mysql_fetch_row(result))) {
        int *l = (int *)mysql_fetch_lengths(result);
        // print F1
        strncpy(buf,row[name2index["F1"]] ? row[name2index["F1"]] : "NULL",row[name2index["F1"]] ? l[name2index["F1"]] : 4);
        buf[row[name2index["F1"]] ? l[name2index["F1"]] : 4] = '\0';
        cout << " " << buf;
        // print F2
        strncpy(buf,row[name2index["F2"]] ? row[name2index["F2"]] : "NULL",row[name2index["F2"]] ? l[name2index["F2"]] : 4);
        buf[row[name2index["F2"]] ? l[name2index["F2"]] : 4] = '\0';
        cout << " " << buf;
        cout << endl;
    }
    delete[] buf;
    mysql_free_result(result);
    mysql_close(handle);
    return 0;
}
