perl数组搜索mysql结果

时间:2014-09-20 09:47:26

标签: mysql arrays linux perl

我有一个包含手机号码的数据库。如何编写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;
    }
}

1 个答案:

答案 0 :(得分:2)

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

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";
}