// Collection of code snippets by Arne VajhÃ¸j 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
#include <cstdio>
#include <cstdlib>

#include <iostream>

using namespace std;

#include "mysql.h"

int main()
{
    //
    // åben connection til:
    //   server = "localhost"
    //   username = "root"
    //   password = ""
    //   database = "Test"
    //   port = 0 (bliver opfattet som default 3306)
    //
    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);
    }
    // udfør query
    mysql_query(handle, "SELECT * FROM t1");
    MYSQL_RES *result = mysql_store_result(handle);
    // print resultat af query
    int nfields = mysql_num_fields(result);
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        int *l = (int *)mysql_fetch_lengths(result);
        for (int i=0; i<nfields; i++) {
            char *buf = new char[l[i]+1];
            strncpy(buf,row[i] ? row[i] : "NULL",row[i] ? l[i] : 4);
            buf[row[i] ? l[i] : 4] = '\0';
            cout << " " << buf;
            delete[] buf;
        }
        cout << endl;
    }
    // luk query
    mysql_free_result(result);
    // luk connection
    mysql_close(handle);
    return 0;
}
