如何使用 DBD::CSV 的 LIKE 运算符找到文字 %?

发布于 2024-08-17 00:09:51 字数 612 浏览 10 评论 0原文

如何使用 LIKE 运算符查找文字 %?

#!/usr/bin/perl
use warnings;
use strict;

use DBI;

my $table = 'formula';
my $dbh = DBI->connect ( "DBI:CSV:", undef, undef, { RaiseError => 1 } );

my $AoA = [ [ qw( id formula ) ], 
        [ 1, 'a + b' ], 
        [ 2, 'c - d' ], 
        [ 3, 'e * f' ], 
        [ 4, 'g / h' ], 
        [ 5, 'i % j' ],     ];

$dbh->do( qq{ CREATE TEMP TABLE $table AS IMPORT ( ? ) }, {}, $AoA ); 

my $sth = $dbh->prepare ( qq{ SELECT * FROM $table WHERE formula LIKE '%[%]%' } );
$sth->execute;
$sth->dump_results;

# Output:
# 3, 'e * f'
# 1 rows

How do I find a literal % with the LIKE-operator?

#!/usr/bin/perl
use warnings;
use strict;

use DBI;

my $table = 'formula';
my $dbh = DBI->connect ( "DBI:CSV:", undef, undef, { RaiseError => 1 } );

my $AoA = [ [ qw( id formula ) ], 
        [ 1, 'a + b' ], 
        [ 2, 'c - d' ], 
        [ 3, 'e * f' ], 
        [ 4, 'g / h' ], 
        [ 5, 'i % j' ],     ];

$dbh->do( qq{ CREATE TEMP TABLE $table AS IMPORT ( ? ) }, {}, $AoA ); 

my $sth = $dbh->prepare ( qq{ SELECT * FROM $table WHERE formula LIKE '%[%]%' } );
$sth->execute;
$sth->dump_results;

# Output:
# 3, 'e * f'
# 1 rows

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

香草可樂 2024-08-24 00:09:51

看来您无法使用当前版本的 DBD::CSV 来执行此操作。

您正在使用DBD::CSV模块来访问数据。它使用SQL::Statement模块来处理表达式。我搜索了它的源代码,发现以下代码处理 LIKE sql 语句条件:

## from SQL::Statement::Operation::Regexp::right method
unless ( defined( $self->{PATTERNS}->{$right} ) )
{
    $self->{PATTERNS}->{$right} = $right;
    ## looks like it doen't check any escape symbols
    $self->{PATTERNS}->{$right} =~ s/%/.*/g; 
    $self->{PATTERNS}->{$right} = $self->regexp( $self->{PATTERNS}->{$right} );
}

查看 $self->{PATTERNS}->{$right} =~ s/% /.*/g; 行。它将 LIKE 模式转换为正则表达式。并且它不会对任何转义符号进行任何检查。所有 % 符号都会被盲目地转换为 .* 模式。这就是为什么我认为它还没有实施。

好吧,也许有人会抽出时间来解决这个问题。

Looks like you can't do this with current version of DBD::CSV.

You are using DBD::CSVmodule to access data. It uses SQL::Statement module to handle expresions. I've searched its source code and found that following code handles LIKE sql statement condition:

## from SQL::Statement::Operation::Regexp::right method
unless ( defined( $self->{PATTERNS}->{$right} ) )
{
    $self->{PATTERNS}->{$right} = $right;
    ## looks like it doen't check any escape symbols
    $self->{PATTERNS}->{$right} =~ s/%/.*/g; 
    $self->{PATTERNS}->{$right} = $self->regexp( $self->{PATTERNS}->{$right} );
}

Look at $self->{PATTERNS}->{$right} =~ s/%/.*/g; line. It converts LIKE pattern to regexp. And it doesn't do any check of any escape symbols. All % symbols are blindly translated to .* pattern. That's why I think it's not implemented yet.

Well, may be someone'll find time to fix this issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文