简体   繁体   中英

Getting the max row character length in a query using Perl DBI Mysql

Using: Perl v5.10.1, MySQL 5.5.15, DBI.

I need to deliver end users output from a database via email. They do not want this as an attachment, but in the body.

I'd like to deliver the data in an ascii table and am having issues determining if DBI has built in functions to do this (output similar to querying MySQL from the command line).

Or If I can determine the longest row character length I can use that to build the table. I have a way to get the max item length in an array, but I can't wrap my head around doing it with the query results.

my $spacer_length = (reverse sort { $a <=> $b } map { length($_) } @array)[0];

Assuming a generic DBI loop, you could do something like this:

use List::Util qw(max);

...
my @output;
my $max;
while (my @foo = $dbi->fetchrow_array) {
    $max = max($max // (), map length, @foo);
    push @output, \@foo;           # save data for email attachment
}

Using the "defined-or" operator // to avoid an undef warning and possible contamination in case of negative values.

I'm not sure exactly what you're asking for, but if you're looking for the "max row character length" for a given column of a query result, you can do that with SQL:

SELECT MAX(CHAR_LENGTH(col1)) FROM t1

or if you want all of the rows sorted by the length of the values of col1:

SELECT col1,col2 from t1 ORDER BY CHAR_LENGTH(col1) DESC

you can execute these queries using DBI like this:

# $mysql is your DBI connection info
my $query = $mysql->prepare("SELECT col1,col2 from t1 ORDER BY CHAR_LENGTH(col1) DESC");
$query->execute();

and then iterate through the result rows:

while ( my @result = $query->fetchrow_array ) {

    my ($col1,$col2) = @result;
    # do stuff with the values

}

and you can print the values as you wish, including like the output from the command line mysql client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM