Wie bekomme ich die Datenbankstruktur mit DBI heraus?
Inhalt:
Mir passiert es immer wieder, dass ich mehr über eine Datenbank erfahren möchte, aber ich habe keinerlei Informationen über die Struktur. Nicht immer stehen Administrationstools zur Verfügung (so zuletzt geschehen mit einer Access-DB nur mit der Access Runtime von Microsoft).
Zum Glück bietet DBI Möglichkeiten, an Informationen über die Struktur zu kommen:
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
my $dsn = 'DBI:ODBC:driver=Microsoft Access-Treiber (*.mdb); dbq=Test';
my $dbh = DBI->connect( $dsn ) or die $DBI::errstr;
my $tables = _get_structure( $dbh );
print join "\n", @$tables;
sub _get_structure{
my ($dbh) = @_;
my @table_creates;
my @data;
my %table_info;
my @tables = $dbh->tables('','','%','TABLE');
my ($sth) = $dbh->column_info(undef,undef,undef,'%') or die $dbh->errstr();
while( my $row = $sth->fetchrow_hashref ){
next unless grep{ $_ =~ $row->{TABLE_NAME} }@tables;
my $type = $row->{TYPE_NAME};
$type .= '('.$row->{COLUMN_SIZE}.')' if $row->{COLUMN_SIZE};
my $info = ($row->{NULLABLE}) ? '' : 'NOT NULL';
my $col = $dbh->quote_identifier( $row->{COLUMN_NAME} ) . ' ' . $type . ' ' . $info;
push @{ $table_info{ $row->{TABLE_NAME} } },$col;
}
for my $tablename ( keys %table_info ) {
my $quoted_name = $dbh->quote_identifier( $tablename );
my $columns = join ",\n ", @{ $table_info{$tablename} };
my $stmt = qq~CREATE TABLE $quoted_name (
$columns
);
~;
push @table_creates, $stmt;
}
$sth->finish();
return \@table_creates;
}
Ergänzungen, Kommentare
Kommentare werden am besten in folgender Form vorgenommen, damit sie im Inhaltsverzeichnis angezeigt werden (natürlich ohne das <verbatim>):
---+++ Main.??? - 14 Jul 2003 - Betreff