Execute a SELECT command: GNOME Data Access 5 manual

## Execute a SELECT command

Any SQL command in Libgda must be converted to a GdaStatement object which is then executed; if the statement defines some variable (place holders), then variables binding (assigning values to variables) is done at execution time. Each database provider (database driver or adapter) can implement its own parser to be able to parse its specific SQL dialect. Except for binding variables, and for reusability, the GdaStatement object guarantees that it contains only one SQL statement (it's not possible for it to contain several ones separated by a semicolon).

Parsing an SQL statement into a GdaStatement object is the job of an SqlParser.

However when one only wants to run a simple SQL statement, Libgda provides the gda_connection_statement_execute_select_command() function which does everything in one step. The following codes illustrates parsing and executing a SELECT statement:

    GdaSqlParser *parser;
    GdaStatement *stmt;
    GError *error = NULL;

    parser = gda_connection_create_parser (cnc);
    if (!parser) {
        /* the database provider used by cnc does not implement its own parser,
         * let's use a generic one */
        parser = gda_sql_parser_new ();
    stmt = gda_sql_parser_parse_string (parser, "SELECT * FROM customers", NULL, &error);
    g_object_unref (parser);
    if (!stmt) {
        /* there was an error while parsing */
    }
    else {
        GdaDataModel *model;
        model = gda_connection_statement_execute_select (cnc, stmt, NULL, &error);
        if (model) {
            /* dump to results to STDOUT */
            gda_data_model_dump (model, stdout);
            g_object_unref (model);
        }
        else {
            /* there was an error while executing the statement */
        }
    }
    g_object_unref (stmt);