【问题标题】:How to check a variable is it the Database and print it out?如何检查变量是否是数据库并将其打印出来?
【发布时间】:2014-04-23 11:15:55
【问题描述】:

我得到了一个变量列表来循环访问数据库。如何检测变量不在数据库中?我应该使用什么查询?一旦检测到变量不在数据库中,如何打印出错误消息。

我的代码:

$variable = $sql->{'variable'};

foreach my $sql (@Records){

**Below statement will select existed variable, what should I change to make it select not existed variable**

$sqlMySQL = "Select LOT from table where LOT like '%$variable%'";

}

**If not exist**{

print("Not exist")

}

预期结果:

当$variable循环数据库时,如果$variable在数据库中不存在则打印出$variable或者不存在。

感谢观看、cmets 和回答。

【问题讨论】:

    标签: sql perl


    【解决方案1】:

    我会按照下面的方法进行。

    1. 变量列表 - 将这些变量放入数组(也称为列表)中
    2. 我应该使用什么查询 - 一个只会准确选择您需要的内容并将其存储在最佳数据集中进行遍历的查询 (selectall_hashref)
    3. 虽然 $variable 循环遍历数据库 - 需要为每个 $variable 调用 DBI,因此请改为遍历数组以检查散列中是否存在。

    示例

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use DBI;
    my $dbh =
      DBI->connect( "dbi:SQLite:dbname=test.db", "USERNAME", "PASSWORD",
        { RaiseError => 1 },
      ) or die $DBI::errstr;
    my @vars = ( 25, 30, 40 );
    my $hash_ref =
      $dbh->selectall_hashref( q / SELECT LOT FROM table /, q / LOT / );
    $dbh->disconnect();
    
    foreach (@vars) {
        if ( exists $hash_ref->{$_} ) {
            print $_ . "\n";
        }
        else {
            print "Does not exist\n";
        }
    }
    

    类似的方法会将您表的所有 LOT 列值拉到一个哈希 key value 对中,然后您可以在 foreach 循环中与您的 array 进行比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2023-03-26
      • 1970-01-01
      • 2013-01-26
      • 2017-03-31
      相关资源
      最近更新 更多