How can I get column names and row data in order with DBI in Perl?

前端 未结 5 1100
天涯浪人
天涯浪人 2021-02-19 22:42

I\'m using DBI to query a SQLite3 database. What I have works, but it doesn\'t return the columns in order. Example:

Query:  select col1, col2, col3, col4 from         


        
5条回答
  •  广开言路
    2021-02-19 23:38

    Replace the "what goes here" comment and the following loop with:

    my $fields = join(',', @{ $result->{NAME_lc} });
    print "$fields\n";
    
    while (my $row = $result->fetchrow_arrayref) {
        my $csv = join(',', @$row);
        print "$csv\n";
    }
    

    NAME_lc gives the field names in lowercase. You can also use NAME_uc for uppercase, or NAME for whatever case the database decides to return them in.

    You should also probably be using Text::CSV or Text::CSV_XS instead of trying to roll your own CSV file, but that's another question.

提交回复
热议问题