【问题标题】:perl array search on mysql resultsperl数组搜索mysql结果
【发布时间】:2014-11-14 20:21:09
【问题描述】:

我有一个包含手机号码的数据库。如何编写将所有数字放入数组并检查新数字是否已存在于该数组中的 perl 脚本?

创建表:

CREATE TABLE consumeruser (
  ConsumerId    int(10) NOT NULL AUTO_INCREMENT,
  ConsumerName  varchar(45) DEFAULT NULL,
  ConsumerMobNo varchar(10) DEFAULT NULL,
  PRIMARY KEY (ConsumerId)
) ENGINE=InnoDB AUTO_INCREMENT=4494 DEFAULT CHARSET=latin1

脚本:

#!/usr/bin/perl -w
use strict;
use warnings qw(all);

use DBI;
use Getopt::Long;
use Pod::Usage;
use Text::CSV_XS;

my $username = 'root';         # set your MySQL username
my $password = 'xxxx';         # set your MySQL password
my $database = 'app';          # set your MySQL database name
my $server   = 'localhost';    # set your server hostname (probably localhost)

my $dbh = DBI->connect( "DBI:mysql:$database;host=$server", $username, $password )
    || die "Could not connect to database: $DBI::errstr";

my $CustomerMobileNumber = 9999999;
my @MobileNumbers;
my $mobileNumberQuery = "select ConsumerMobNo from consumeruser";
my $sth               = $dbh->prepare($mobileNumberQuery);
$sth->execute();
while ( my @row = $sth->fetchrow_array() ) {
    push @MobileNumbers, $row;

    if (/test for is present/) {
        #9999999 found in array;
    } else {
        #9999999 not found in array;
    }
}

【问题讨论】:

  • 不是将所有数字从数据库中取出并放入数组中,而是使用 SELECT 查询来查看数据库中是否存在该数字。

标签: mysql arrays linux perl


【解决方案1】:

您可以要求数据库搜索号码:

my $mobileNumberQuery = "SELECT 1 FROM consumeruser WHERE ConsumerMobNo = ?";
my $sth = $dbh->prepare($mobileNumberQuery);
$sth->execute(9999999);
if ($sth->fetchrow_array) {
    print "Found.\n"
} else {
    print "Not found.\n";
}

【讨论】:

  • 实际上我有一个 CSV 文件,其中包含我想用数据库检查的手机号码,因为我想避免为每个手机号码选择查询
猜你喜欢
  • 2017-12-04
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 2016-04-30
  • 2014-11-25
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多