Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I get column names and row data in order with DBI in Perl?
    primarykey
    data
    text
    <p>I'm using DBI to query a SQLite3 database. What I have works, but it doesn't return the columns in order. Example:</p> <pre><code>Query: select col1, col2, col3, col4 from some_view; Output: col3, col2, col1, col4 3, 2, 1, 4 3, 2, 1, 4 3, 2, 1, 4 3, 2, 1, 4 ... (values and columns are just for illustration) </code></pre> <p><strong>I know this is happening because I'm using a hash</strong>, but how else do I get the column names back if I only use an array? All I want to do is get something like this for any <strong>arbitrary</strong> query:</p> <pre><code> col1, col2, col3, col4 1, 2, 3, 4 1, 2, 3, 4 1, 2, 3, 4 1, 2, 3, 4 ... </code></pre> <p>(That is, I need the output is in the right order and with the column names.)</p> <p>I'm very much a Perl novice, but I really thought this would be a simple problem. (I've done this before in Ruby and PHP, but I'm having trouble tracking down what I'm looking for in the Perl documentation.)</p> <p>Here's a pared down version of what I have at the moment:</p> <pre><code>use Data::Dumper; use DBI; my $database_path = '~/path/to/db.sqlite3'; $database = DBI-&gt;connect( "dbi:SQLite:dbname=$database_path", "", "", { RaiseError =&gt; 1, AutoCommit =&gt; 0, } ) or die "Couldn't connect to database: " . DBI-&gt;errstr; my $result = $database-&gt;prepare('select col1, col2, col3, col4 from some_view;') or die "Couldn't prepare query: " . $database-&gt;errstr; $result-&gt;execute or die "Couldn't execute query: " . $result-&gt;errstr; ########################################################################################### # What goes here to print the fields that I requested in the query? # It can be totally arbitrary or '*' -- "col1, col2, col3, col4" is just for illustration. # I would expect it to be called something like $result-&gt;fields ########################################################################################### while (my $row = $result-&gt;fetchrow_hashref) { my $csv = join(',', values %$row); print "$csv\n"; } $result-&gt;finish; $database-&gt;disconnect; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload