dbi intermediate

How to use Perl DBI selectall_arrayref for fetching all data?

Question

How to use Perl DBI selectall_arrayref for fetching all data?

The selectall_arrayref method in Perl's DBI module is a convenient way to run a SELECT query and fetch all rows in one call. It returns a reference to an array of rows, where each row is either an arrayref (AoA) or, optionally, a hashref (AoH) depending on attributes passed.

What is selectall_arrayref?

selectall_arrayref combines preparing, executing, and fetching results in a single method call. You provide the SQL statement, optional statement attributes, and optional bind parameters for placeholders. It returns all resulting rows fetched at once as an array reference.

selectall_arrayref is typically called on a valid database handle ($dbh), which you obtain from DBI->connect. If you see errors like Can't call method "selectall_arrayref" on an undefined value, it means your database handle was not created correctly or is undefined.

Basic usage and context

  • By default, it returns an arrayref of arrayrefs where each inner arrayref is a row of column values.
  • To get an arrayref of hashrefs keyed by column names instead, pass the attribute { Slice => {} }.
  • You can bind parameters to placeholders by adding values after the attributes argument.
  • Ensure your DBI handle ($dbh) is properly connected before calling this method.

Runnable Example Using an In-Memory SQLite Database

The example below illustrates connecting to an in-memory SQLite database (which comes with the core DBD::SQLite module if your Perl installation supports it), creating a table, inserting data, and fetching all results both as AoA and AoH using selectall_arrayref.


use strict;
use warnings;
use DBI;

# Connect to an in-memory SQLite database
my $dbh = DBI->connect("dbi:SQLite:dbname=:memory:", "", "", {
    RaiseError => 1,
    PrintError => 0,
    AutoCommit => 1,
}) or die "Failed to connect to database";

# Create table and insert rows
$dbh->do("CREATE TABLE fruits (id INTEGER PRIMARY KEY, name TEXT, color TEXT)");
$dbh->do("INSERT INTO fruits (name, color) VALUES (?, ?)", undef, "Apple", "Red");
$dbh->do("INSERT INTO fruits (name, color) VALUES (?, ?)", undef, "Banana", "Yellow");
$dbh->do("INSERT INTO fruits (name, color) VALUES (?, ?)", undef, "Grape", "Purple");

# Fetch all rows as array of arrays (AoA)
my $rows_aoa = $dbh->selectall_arrayref("SELECT id, name, color FROM fruits ORDER BY id");

print "Results as array of arrays:\n";
for my $row (@$rows_aoa) {
    printf "ID: %d, Name: %s, Color: %s\n", @$row;
}

# Fetch all rows as array of hashes (AoH) using Slice
my $rows_aoh = $dbh->selectall_arrayref("SELECT id, name, color FROM fruits ORDER BY id", { Slice => {} });

print "\nResults as array of hashes:\n";
for my $row (@$rows_aoh) {
    printf "ID: %d, Name: %s, Color: %s\n", $row->{id}, $row->{name}, $row->{color};
}

# Disconnect cleanly
$dbh->disconnect;

Common Pitfalls and Notes

  • Undefined database handle: Always check your DBI->connect succeeded before calling methods on $dbh.
  • Attributes parameter: The second parameter to selectall_arrayref is optional. Use undef if you want to skip attributes but supply bind values.
  • Memory considerations: This method fetches all rows at once—beware with large data sets.
  • DBD::SQLite: The example uses SQLite in-memory DB, which requires DBD::SQLite installed (core in many Perl distributions).
  • Context awareness: The method is flexible but the return structure changes based on attributes.

Summary

selectall_arrayref is a terse and handy way to grab all records from a SELECT query as an arrayref of rows, either arrays or hashes. Always ensure your DBI connection is valid and choose the right attributes to suit how you want to access your data. It demonstrates Perl’s TMTOWTDI ("There's More Than One Way To Do It") philosophy by letting you pick your return format.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 43ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Results as array of arrays:
ID: 1, Name: Apple, Color: Red
ID: 2, Name: Banana, Color: Yellow
ID: 3, Name: Grape, Color: Purple

Results as array of hashes:
ID: 1, Name: Apple, Color: Red
ID: 2, Name: Banana, Color: Yellow
ID: 3, Name: Grape, Color: Purple
STDERR
(empty)

Was this helpful?

Related Questions