Depending on your database driver, you may* be able to use type hints in bind_col
:
use DBI qw(:sql_types);
...
my $sth = $dbh->prepare('SELECT id, name FROM foos WHERE name = "bar"');
$sth->execute;
$sth->bind_col(1, undef, {
TYPE => SQL_INTEGER,
StrictlyTyped => 1,
DiscardString => 1
});
while (my $hr = $sth->fetchrow_hashref) {
say to_json $hr;
}
This attempts to bind the first column (indexed from one) to the SQL_INTEGER
type and throws an error if the cast fails for any value. As bohica notes, the DiscardString
attribute is necessary because it "throws away the string portion of your data (the pv)."
* According to the DBI documentation:
Few drivers support specifying a data type via a
bind_col
call (most will simply ignore the data type).
DBD::Oracle
and DBD::ODBC
support it, and DBD::Pg
may support it, according to this thread (although I can't verify it), while DBD::mysql
doesn't. I'm not sure about other drivers.