http://qs321.pair.com?node_id=25303


in reply to Field names of database table from DBI

The short answer is, no, there's not a cleaner, portable way to get a list of field names without doing some kind of select statement. If you don't mind sacrificing a little portability, you can use a driver-specific way to do it. For example, in DBD::mysql, you could do
my $sth = $dbh->prepare("LISTFIELDS $table"); $sth->execute; my $names_aref = $sth->{NAME};
Check your appropriate DBD::driver manpage for more specific details if you choose to go this route.

Replies are listed 'Best First'.
RE: Re: Field names of database table from DBI
by jettero (Monsignor) on Aug 01, 2000 at 16:08 UTC
    I'm pretty sure LISTFIELDS doesn't work in my mysql. I've always used this:
    my $s = $h->prepare("show fields from $table"); $s->execute; $s->bind_col(1, \$name); push @names, $name while($s->fetch);
      SHOW COLUMNS FROM $table should also work
      #!/usr/bin/perl # connect to db my $dbh = DBI->connect(bla..bla..bla); my $sql_q = "SHOW COLUMNS FROM $table"; my $sth = $dbh->prepare($sql_q); $sth->execute; while (@row = $sth->fetchrow_array){ print"Field Type Null Key Default Extra\n"; print"----------------------------------------------------\n"; print"$row[0] $row[1] $row[2] $row[3] $row[4] $row[5]\n"; }
        This is database dependant. It won't work for MS SQL through the DBD::ODBC driver, for instance.