Vala PostgreSQL Example

/**
 * To compile:
 *  valac --pkg libpq test.vala -X -lpq 
 */

using GLib;
using Postgres;

public static int main (string[] args)
{
    string conninfo;

    if (args.length > 1) {
        conninfo = args[1];
    } else {
        conninfo = "dbname = postgres";
    }

    /* Make a connection to the database */
    Database conn = Postgres.connect_db (conninfo);

    /* Check to see that the backend connection was successfully made */
    if (conn.get_status () != ConnectionStatus.OK) {
        stderr.printf ("Connection to database failed: %s", conn.get_error_message ());
        return 1;
    }

    /*
     * Our test case here involves using a cursor, for which we must be inside
     * a transaction block.  We could do the whole thing with a single
     * PQexec() of "select * from pg_database", but that's too trivial to make
     * a good example.
     */

    /* Start a transaction block */
    Result res = conn.exec ("BEGIN");
    if (res.get_status () != ExecStatus.COMMAND_OK) {
        stderr.printf ("BEGIN command failed: %s", conn.get_error_message ());
        return 1;
    }

    /*
     * Fetch rows from pg_database, the system catalog of databases
     */
    res = conn.exec ("DECLARE myportal CURSOR FOR select * from pg_database");
    if (res.get_status () != ExecStatus.COMMAND_OK) {
        stderr.printf ("DECLARE CURSOR failed: %s", conn.get_error_message ());
        return 1;
    }

    res = conn.exec ("FETCH ALL in myportal");
    if (res.get_status () != ExecStatus.TUPLES_OK) {
        stderr.printf ("FETCH ALL failed: %s", conn.get_error_message ());
        return 1;
    }

    /* first, print out the attribute names */
    int nFields = res.get_n_fields ();
    for (int i = 0; i < nFields; i++) {
        stdout.printf ("%-15s", res.get_field_name (i));
    }
    stdout.printf ("\n\n");

    /* next, print out the rows */
    for (int i = 0; i < res.get_n_tuples(); i++) {
        for (int j = 0; j < nFields; j++) {
            stdout.printf ("%-15s", res.get_value (i, j));
        }
        stdout.printf ("\n");
    }

    ConnectionOptions opt = Postgres.get_default_options ();
    stdout.printf ("label=%s, keyword=%s\n", opt.label, opt.keyword);

    stdout.printf ("db=%s, user=%s, passwd=%s, host=%s, port=%s, tty=%s, options=%s\n", conn.get_db (), conn.get_user (), conn.get_passwd (), conn.get_host (), conn.get_port (), conn.get_tty (), conn.get_options ());

    /* close the portal ... we don't bother to check for errors ... */
    res = conn.exec ("CLOSE myportal");

    /* end the transaction */
    res = conn.exec ("END");

    return 0;
}

Projects/Vala/PostgreSQL (last edited 2013-11-22 16:48:30 by WilliamJonMcCann)