【问题标题】:Perl SQLite DBI SELECT with bind not workingPerl SQLite DBI SELECT 绑定不起作用
【发布时间】:2014-02-26 08:07:31
【问题描述】:

为什么此示例代码中的第二个 SELECT 语句返回空结果?

use DBI;
use Data::Dumper;

my $dbh = DBI->connect('dbi:SQLite:dbname=test.db', '', '', { AutoCommit =>1, PrintError => 1, RaiseError => 1 }) or die $DBI::errstr;

my $r = $dbh->selectall_arrayref('select 123 where 5 > 2', { Slice => {} }) or die $dbh->errstr;

print Dumper $r;

$r = $dbh->selectall_arrayref('select 123 where 5 > ?', { Slice => {} }, 2) or die $dbh->errstr;

print Dumper $r;

输出

$VAR1 = [
          {
            '123' => 123
          }
        ];
$VAR1 = [];

【问题讨论】:

    标签: perl sqlite select bind dbi


    【解决方案1】:

    DBD::SQLite 文档中是这样说的:

    这是因为 DBD::SQLite 默认假定所有绑定值都是文本(并且应该被引用)。

    一种解决方法是:

    $r = $dbh->selectall_arrayref('select 123 where 5 > (?+0)', { Slice => {} }, 2)
        or die $dbh->errstr;
    

    另一种可能更好的方法是在查询之前设置 sqlite_see_if_its_a_number 数据库句柄属性,甚至在连接时。

    $dbh->{sqlite_see_if_its_a_number}=1;
    

    【讨论】:

    • 如果我是你,我实际上会使用 ikegami 提供的第一个示例。 sqlite_see_if_its_a_number 有一些可怕的后果,可能会让你失望。例如,尝试将 '1.2340' 插入带有 sqlite_see_if_its_a_number 的 char 列中,您将丢失尾随的 0。
    【解决方案2】:

    试试这个:

    $r = $dbh->selectall_arrayref('select 123 where 5 > 0+?', { Slice => {} }, 2);
    

    或者,做:

    my $sth = $dbh->prepare('select 123 where 5 > ?');
    $sth->bind_param(1, 2, DBI::SQL_INTEGER);
    $sth->execute;
    $r = $sth->fetchall_arrayref({});
    

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2012-11-13
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 2014-11-30
      • 1970-01-01
      相关资源
      最近更新 更多