[英]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.