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

#include "mysql.h"

int main()
{
    /* connection */
    MYSQL *handle;
    /* query result */
    MYSQL_RES *result;
    /* række i query result */
    MYSQL_ROW row;
    /* antal felter i query result */
    int nfields;
    /* pointer til array med felt længder i række i query resuult */
    int *l;
    /* counter */
    int i;
    /*
     * åben connection til:
     *   server = "localhost"
     *   username = "root"
     *   password = ""
     *   database = "Test"
     *   port = 0 (bliver opfattet som default 3306)
     */
    handle= mysql_init(NULL);
    if(handle == NULL)
    {
        printf("MySQL error: %s", mysql_error(handle));
        exit(1);
    }
    if(!mysql_real_connect(handle, "localhost", "root", "", "Test", 0, NULL, 0))
    {
        printf("MySQL error: %s", mysql_error(handle));
        exit(1);
    }
    /* udfør query */
    mysql_query(handle, "SELECT * FROM t1");
    result = mysql_store_result(handle);
    /* print resultat af query */
    nfields = mysql_num_fields(result);
    while ((row = mysql_fetch_row(result))) {
        l = (int *)mysql_fetch_lengths(result);
        for (i=0; i<nfields; i++) {
            printf(" %.*s", row[i] ? l[i] : 4, row[i] ? row[i] : "NULL");
        }
        printf("\n");
    }
    /* luk query */
    mysql_free_result(result);
    /* luk connection */
    mysql_close(handle);
    return 0;
}
