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

前端 未结 5 1101
天涯浪人
天涯浪人 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:18

    Define your column names in an ARRAY before your SELECT

    Ideally you'd have a list of the columns you were SELECT'ing with DBI, and you'd use that array.

    If you need to get the column names from the hash itself, this will work, and you can sort it, but there is no indication of the original SQL SELECT order (in the hash):

    my %cols_hash = ("name" => "john", "age" => 2, "color" => "apalachian");
    my $cols_hash_ref = \%cols;  
    
    my @keys = (sort keys %$cols_hash_ref);  
    my @vals;  
    foreach (@keys){ push @vals, $$cols_hash_ref{$_} };  
    

    Hope this helps.

    When I searched I found a way to get the column names from the DBI:

    $sth = $dbh->prepare($query) or die "Prepare exceptioin: $DBI::errstr!";  
    $rv = $sth->execute() or die "Execute exception: $DBI::errstr";  
    $res = $sth->fetchall_arrayref();  
    
    # Array reference with cols captions, which were retrived.  
    $col_names_array_ref = $sth->{NAME};          
    

    That should give you the column names in the original order, but I haven't tested it.

提交回复
热议问题