#!/usr/bin/perl -wT # FILE: show_field_names # Demonstrates # - getting name of database from user and connecting to that database # - showing tables in database selected # - getting name of table from user # - displaying all field names in table selected # Note: what happens if you enter the name of a table that does not exist? # What can you do to avoid this error? use DBI; print "Name of database: "; chomp($name = ); my $db =$name; print "database selected: $db\n"; my $server = "clarke"; print "id: "; chomp($id = ); print "password: "; chomp($pw = ); my $dbh = DBI->connect("DBI:mysql:$db:$server","$id", "$pw") or die("Error: $DBI::errstr"); my @table_list = @{$dbh->selectcol_arrayref("SHOW TABLES")}; print "The available TABLES in $db are: \n"; foreach $_ (@table_list){ print "$_\n"; } print "Which table would you like to see? "; chomp($table_name = ); my $query = qq(select * from $table_name); my $sth = $dbh->prepare($query); $sth->execute; while (my $record = $sth->fetchrow_hashref) { for my $field (keys %$record) { print "$field: $record->{$field}\n"; } } print "\n"; $sth->finish(); $dbh->disconnect;