I've run across a strange bit of behavior within DBI. When I set the 'LongTruncOk' parameter to true for a database handle and retrieve a long string it seems to insert null bytes between each character. For example, a string of '600' comes back as (in hex):

36 00 30 00 30

This pattern persists throughout the string. This does not occur if LongTruncOk is set to false.

Is this expected behavior that I'm simply ignorant of? I want it to automatically truncate strings that are too long, but not if my string gets trashed in the process.

The following code reproduces the problem. I'm working with an MS SQL Server if it matters.

#!/usr/bin/perl use strict; use warnings; use DBI qw(:utils); my $data; my $host = 'somehost'; my $query = <<'END'; select someColumn from someDb.someSchema.someTable where id = someValue END $data = queryDb( 'host' => $host, 'query' => $query, 'longTruncOk' => 1, ); print $data->[0][0], "\n"; #Output as ASCII $data->[0][0] =~ s/(.)/sprintf("%x ",ord($1))/eg; print $data->[0][0], "\n"; #Output as hex sub queryDb { my %args = @_; my $connStr = 'DBI:ODBC:' . $args{host}; my $dbh = DBI->connect($connStr) or die "Couldn't connect to database: " . DBI->errstr . "\n"; my $table = []; $dbh->{LongReadLen} = defined $args{longReadLen} ? $args{longReadLen +} : 80; $dbh->{LongTruncOk} = defined $args{longTruncOk} ? $args{longTruncOk +} : 0; #Note - this seems to change strings to UTF-16? my $sth = $dbh->prepare($args{query}) or die "Couldn't prepare statement: " . $dbh->errstr . "\n"; $sth->execute( @{ $args{params} } ); while (my @row = $sth->fetchrow_array()) { push @$table, \@row; } return $table; }

In reply to DBI Adding Null Bytes to String by Stringer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.