简体   繁体   English

使用Perl DBI Mysql获取查询中的最大行字符长度

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

Using: Perl v5.10.1, MySQL 5.5.15, DBI. 使用: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). 我想将数据传递到ascii表中,并且在确定DBI是否具有内置函数来执行此操作时遇到问题(输出类似于从命令行查询MySQL)。

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: 假设有一个通用的DBI循环,您可以执行以下操作:

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. //使用“定义或”运算符//避免出现undef警告,并在出现负值时可能造成污染。

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: 我不确定您到底要问什么,但是如果您要为查询结果的给定列寻找“最大行字符长度”,则可以使用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: 或者,如果您希望所有行按col1值的长度排序:

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

you can execute these queries using DBI like this: 您可以像这样使用DBI执行这些查询:

# $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. 并且您可以根据需要打印这些值,包括从命令行mysql客户端输出的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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