繁体   English   中英

选择count(*)不适用于perl DBI

[英]select count(*) not working with perl DBI

我的代码的目标是基于一个特定参数返回表中的行数计数。

这是有效的代码:

######### SQL Commands
### Connect to the SQL Database
my $dbh = DBI->connect($data_source, $user, $pass)
    or die "Can't connect to $data_source: $DBI::errstr";

### Prepare the SQL statement and execute
my $sth1 = $dbh->selectrow_array("select count(*) from TableInfo where Type = '2'")
or die "Can't connect to $data_source: $DBI::errstr";

### Disconnect from Database statements are completed.
$dbh->disconnect;
######### end SQL Commands 


print $sth1;

在这种情况下,这将成功打印一个数字189。 当我尝试使用相同的代码但更改“ Type ='2'”(应返回值2000)时,出现以下错误:

DBD::ODBC::db selectrow_array failed: [Microsoft][ODBC Driver 11 for SQL Server]Numeric value out of range (SQL-22003) at ./getTotalExpSRP.cgi line 33, <DATA> line 225.
Can't connect to dbi:ODBC:BLTSS_SRP: [Microsoft][ODBC Driver 11 for SQL Server]Numeric value out of range (SQL-22003) at ./getTotalExpSRP.cgi line 33, <DATA> line 225.

我到处都在搜索,但找不到原因。 从问题的症状来看,我猜想返回结果的大小是有限的,但是我找不到任何支持的证据。

我已经在Microsoft SQL 2005服务器上运行了跟踪,并且可以确认sql语句是否正确运行,没有错误。

我已经查看了odbc跟踪日志,但不幸的是,在将一个有效示例与一个失败示例进行比较时,我无法获得任何有用的信息。

任何帮助,将不胜感激!!

谢谢,

现在,我们已经看到了可以解释的痕迹。 DBD :: ODBC调用SQLDescribeCol并被告知:

DescribeCol列= 1,name =,namelen = 0,type = unknown(0),precision / column size = 10,scale = 0,nullable = 1 display size = 11

然后,它调用SQLColAttribute,并告知列大小为4。由于列类型未知(为什么驱动程序不确定,我不确定),所以DBD :: ODBC决定将列绑定为char(4),因此尽快因为计数> 3位数字,它将溢出。

这里使用的DBI和DBD :: ODBC版本确实很旧,我怀疑最新版本可以更好地解决此问题。

Numeric value out of range是类型转换错误。 TYPE是否应该是一个字符/字符串的数字? 如果应该是数字,请使用数字

my $sth1 = $dbh->selectrow_array(
    "select count(*) from TableInfo where Type=2")  # Type=2, not Type='2'

或使用占位符,让Perl和数据库驱动程序担心类型转换

my $sth = $dbh->prepare("select count(*) from TableInfo where Type=?");
$sth->execute(2);
$sth->execute('2');     # same thing
my $st1 = $sth->fetchall_arrayref;

暂无
暂无

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

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