Save the following code to the (for example) sample.c file and compile with:

cc -Wall -o sample sample.c `pkg-config --cflags --libs libgda-4.0`

Run the ./sample program without any argument. The SQL run in this example selects all the fields of the customers table using the default SalesTest DSN installed by Libgda the first time you run an application using Libgda.

#include <libgda.h>

int
main (int argc, char *argv[])
{
        GdaConnection *cnc;
        gchar *dsn = "SalesTest";
        GError *error = NULL;

        gda_init ();

        /* Open the connection to the database, using the SalesTest DSN, a
         * data source defined when Libgda is installed which points to a simple
         * SQLite database
         */
        cnc = gda_connection_open_from_dsn (dsn, NULL,
                                            GDA_CONNECTION_OPTIONS_NONE,
                                            &error);
        if (!cnc) {
                g_print ("Could not open connection to DSN '%s': %s\n",
                         dsn,
                         error && error->message ? error->message : "No detail");
                exit (1);
        }

        /* execute a SELECT statement; here the easiest API is used */
        GdaDataModel *data_model;
        data_model = gda_execute_select_command (cnc, "SELECT * FROM customers", &error);
        if (!data_model) {
                g_print ("Could not execute the SQL command: %s\n",
                         error && error->message ? error->message : "No detail");
                /* close the connection */
                g_object_unref (cnc);
                exit (1);
        }
        
        /* dump the output to the standard output */
        gda_data_model_dump (data_model, NULL);
        g_object_unref (data_model);
        g_object_unref (cnc);

        return 0;
}

The result of the execution should be something similar to the following output:

id | name            | default_served_by | country | city
---+-----------------+-------------------+---------+-----
 2 | Ed Lamton       |                 4 | SP      | MDR 
 3 | Lew Bonito      |                 1 | FR      | TLS 
 4 | Mark Lawrencep  |              NULL | SP      | MDR 
 9 | Greg Popoff     |                 2 | SP      | MDR 
10 | Vladimir Zirkov |                 4 | NULL    | NULL
(5 rows)

CodeExampleGdaSelect (last edited 2010-07-01 20:02:03 by VivienMalerba)