Dave's Brain

Browse - programming tips - postgresql get field names programatically

Date: 2011feb16
Language: Perl

Q.  How can I programatically get the field names for a Postgresql table?

A.  Here's a routine that does it provided the table isn't empty.

# Doesn't return the field names in schema order
sub getTableFields($$)
{
        my($dbh, $table) = @_;
        my($sql, $sth, $ref, @out);

        $sql = qq(SELECT * FROM $table LIMIT 1);
        $sth = $dbh->prepare($sql);
        if (!defined $sth) { return @out }
        if (!$sth->execute()) { return @out }
        while ($ref = $sth->fetchrow_hashref())
        {
                @out = keys %$ref;
        }
        $sth->finish();
        return @out;
}

Do you know of a better way?  Please leave a comment.
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: