0

How to I have to change this script to get the BLOB output truncated?

#!/usr/bin/env perl
use warnings;
use strict;
use utf8;
use 5.10.1;
use DBI;

my $user = 'username';
my $passwd = 'password';

my $db = 'information_schema';
my $dbh = DBI->connect( "DBI:mysql:dbname=$db", $user, $passwd, {
    RaiseError => 1,
    AutoCommit => 1,
} ) or die DBI->errstr;

$db = 'test_truncate';
$dbh->do( "DROP DATABASE IF EXISTS $db" );
$dbh->do( "CREATE DATABASE $db" );

$dbh = DBI->connect( "DBI:mysql:dbname=$db", $user, $passwd, {
    PrintError => 0,
    RaiseError => 1,
    AutoCommit => 1,
    mysql_enable_utf8 => 1,
} ) or die DBI->errstr;

$dbh->{LongReadLen} = 5;
$dbh->{LongTruncOk} = 1;

my $table = 'table_truncate';
$dbh->do( "CREATE TABLE IF NOT EXISTS $table ( Id INT, my_Blob BLOB )" );
my $sth = $dbh->prepare( "INSERT INTO $table ( Id, my_Blob ) VALUES ( ?, ? )" );

my $blob = '123456789' x 20;
$sth->execute( 1, $blob );

$sth = $dbh->prepare( "SELECT * FROM $table" );
$sth->execute();
while ( my $row = $sth->fetchrow_arrayref() ) {
    say for @$row;
}

Outputs:

1
123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789
sid_com
  • 24,137
  • 26
  • 96
  • 187

1 Answers1

1

adjust the output like this

while ( my $row = $sth->fetchrow_arrayref() ) {
    print substr($_,0,78)."\n" for @$row;
}
Vorsprung
  • 32,923
  • 5
  • 39
  • 63
  • Do you mean I could use `substr` instead of `LongReadLen` and `LongTruncOk`? – sid_com Jan 24 '13 at 16:36
  • LongReadLen will limit the number of bytes read from the database by the fetchfow. substr limits the number of bytes displayed. They operate at different points. Using substr at the final place where the data is shown to the user limits what the user sees. Using substr does not limit the amount of data flowing between the database server and the client program. LongReadLen limits the amount of data flowing from the database server to the client program – Vorsprung Jan 25 '13 at 09:41