Specifically for mysql, you can use a special SQL command:
DESCRIBE $table. Yes that works in DBI too. Here's a test table "foo", which I put into the database "test" (present by default):
CREATE TABLE foo(
id int(10) unsigned NOT NULL AUTO_INCREMENT,
letter char(1) NOT NULL,
name text NOT NULL,
num float NULL,
PRIMARY KEY (id)
);
And here's some demo code checking what we've got:
#!/usr/local/bin/perl -w
use DBI;
my $dbh = DBI->connect('dbi:mysql:test', "", "", { PrintError => 0 , R
+aiseError => 1});
END { $dbh->disconnect if $dbh }
use Data::Dumper;
my $sth = $dbh->prepare('DESCRIBE foo');
$sth->execute;
while(my $r = $sth->fetchrow_hashref) {
print Dumper $r;
}
which shows:
$VAR1 = {
'Extra' => 'auto_increment',
'Field' => 'id',
'Default' => undef,
'Key' => 'PRI',
'Type' => 'int(10) unsigned',
'Null' => ''
};
$VAR1 = {
'Extra' => '',
'Field' => 'letter',
'Default' => '',
'Key' => '',
'Type' => 'char(1)',
'Null' => ''
};
$VAR1 = {
'Extra' => '',
'Field' => 'name',
'Default' => '',
'Key' => '',
'Type' => 'text',
'Null' => ''
};
$VAR1 = {
'Extra' => '',
'Field' => 'num',
'Default' => undef,
'Key' => '',
'Type' => 'float',
'Null' => 'YES'
};
4 records, one for each field. 'Field' contains the field name. In particular, check out the contents of the field 'Key': its value is "PRI" for the primary key, the empty string for the rest.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.