
FishMonger
Veteran
Nov 3, 2008, 8:34 AM
Post #3 of 4
(3743 views)
|
|
Re: [aesalus1976] export from database to dbf
[In reply to]
|
Can't Post
|
|
Please use the code tags when posing blocks of code. The code tags will use a different font and retain the code indentation which will make it easier for us to read. Instead of using the -w switch, it's better to use the warnings pragma as well as the strict pragma. Instead of the if (!$dbh) { block use an or die statement on the connect statement and enable RaiseError. Your method of building/assigning the @nm and @nm1 arrays is very messy and inefficient. Your while loop is not initialized properly and the $table->set_record call should be passed the row that was fetched in the begining of the loop, not a separate fetch_array call. Here is a cleaned up version, but it's incomplete.
#!/usr/bin/perl use warnings; use strict; use XBase; use DBI; use Time::Local; #configuration (for now only) $db = 'database name'; $login = 'user name'; $passwd = 'password'; $tb = 'table name'; #login to database my $dbh = DBI->connect("DBI:Pg:dbname=$db", $login, $passwd, { RaiseError => 1 }) or die "ERR: Couldn't open connection: " . $DBI::errstr."\n"; #setup and execute query my $sth = $dbh->prepare("select * from $tb"); $sth->execute; my @names = @{$sth->{NAME}}; #my @types = @{$sth->{TYPE}}; # returns integer my @types = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} }; # returns name # @types needs to be translated into single character data types that are used by XBase # The field types are specified by one letter strings (C, N, L, D, ...). # If you set some value as undefined, create will make it into some reasonable default. #create empty dbf file my $newtable = XBase->create("name" => "new.dbf", "field_names" => [ @names ], "field_types" => [ @types ], # see above note # the DBI doc should show how to retrieve this info "field_lengths" => [ ], "field_decimals" => [ ], ); #open dbf file my $table = new XBase "copy.dbf" or die XBase->errstr; #add some records while (my @values = $sth->fetchrow_array) { my $last = $table->last_record; $table->set_record($last+1, @values); }
|