Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: adding database values to csv file

by Tux (Abbot)
on Sep 26, 2011 at 08:53 UTC ( #927821=note: print w/replies, xml ) Need Help??

in reply to adding database values to csv file

Buttons are GUI specific, so unless you tell us what the GUI is you want it to be implemented in, it will be hard to get working examples. perl/Tk button code won't work in Wx and vise-versa.

A callback to dump a table to CSV could be something like (untested!)

# assuming the database handle in $dbh use Text::CSV_XS; sub save_table { my $tbl = shift; # it is up to you to check for SQL-injection on $tbl ... my $sth = $dbh->prepare ("select * from $tbl"); $sth->execute; my %rec; my @fld = @{$sth->{NAME_lc}}; $sth->bind_columns (\@rec{@fld}); my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1, eol => + "\n", always_quote => 1 }); $csv->print (*STDOUT, \@fld); # Print header, change STDOUT to fil +e if required while ($sth->fetch) { $csv->print (*STDOUT, [ @rec{@fld} ]); } } # save_table

Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^2: adding database values to csv file
by vsurend (Novice) on Sep 26, 2011 at 09:06 UTC
    I am developing a GUI in perl/tk. Its mainly for report preparation purpose. So When I give the required inputs and Click on 'Generate Report' button I want the query fetched result to be put in a csv file. -Vidya Surendran
      $frame->Button ( -text => "Save table FOO", -borderwidth => 1, -highlightthickness => 0, -command => sub { save_table ("foo"); }, )->pack;

      Enjoy, Have FUN! H.Merijn
Re^2: adding database values to csv file
by Anonymous Monk on Sep 27, 2011 at 11:52 UTC
    I would like to tie on with my question:
    say you need to modify the values bevor printing where could be the best point to do this?
      while ($sth->fetch) { $rec{fobar} =~ s{old}{new}; # change in a single co +lumn s/(?:\b|[0-9])USD\b/EUR/g for values %rec; # change all columns $csv->print (*STDOUT, [ @rec{@fld} ]); }

      Enjoy, Have FUN! H.Merijn
        Many thanks!


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://927821]
[Corion]: Whee! ;)
[Corion]: I was away last week already, so I know how good a week off is ;))
[Discipulus]: a barter with your time (above the poorline time is always better than money)

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2017-02-28 10:16 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (399 votes). Check out past polls.