在一个perl脚本中执行两个查询

时间:2013-09-25 07:12:11

标签: mysql perl

我是perl脚本的新手,我在尝试执行两个sql时发现了一个问题,这里有代码,肯定不是最好的代码。

use DBI;
use DBD::mysql;
use Socket;
use strict;
use warnings;

# CONFIG VARIABLES
my $platform = 'mysql';
my $database = 'database_name';
my $host = 'hostname';
my $port = '3306';
my $user ='user';
my $pw ='password';

# DATA SOURCE NAME
my $dsn = "dbi:mysql:$database:$host:3306";

# PERL DBI CONNECT
my $dbh = DBI->connect($dsn,$user,$pw,{RaiseError=>1,PrintError=>1}) or die "Could not connect to database: $DBI::errstr";

# READ THE LASTID OF THE DATABASE
my $queryID = "SELECT event.id from snorby.event order by event.id desc limit 1";
my $lastid = $dbh->selectrow_array($queryID);

#HIGH
while ( 1 == 1 )
{
my $query = "SELECT event.id, inet_ntoa(iphdr.ip_src) as 'src', tcp_sport, inet_ntoa(iphdr.ip_dst) as 'dst', tcp_dport, signature.sig_name, event.timestamp, unhex(data.data_payload) from snorby.event join snorby.signature on signature.sig_id = event.signature join snorby.iphdr on event.cid=iphdr.cid and event.sid=iphdr.sid join snorby.data on event.cid=data.cid and event.sid=data.sid join snorby.tcphdr on event.cid=tcphdr.cid and event.sid=tcphdr.sid where event.id > $lastid and signature.sig_priority = '1' order by event.id";

my $sth = $dbh->prepare($query);
$sth->execute() or die "SQL Error: $DBI::errstr\n";

# BIND TABLE COLUMNS TO VARIABLES
my($eventid,$src,$sport,$dst,$dport,$signature,$timestamp,$payload);
$sth->bind_columns(undef, \$eventid, \$src, \$sport, \$dst, \$dport, \$signature, \$timestamp, \$payload);

# LOOP THROUGH RESULTS  
while($sth->fetch) {

my $src_temp = inet_aton($src);
my $dst_temp = inet_aton($dst);

print "IT WORKS!";

}

所以,如果我评论这部分代码

# READ THE LASTID OF THE DATABASE
my $queryID = "SELECT event.id from snorby.event order by event.id desc limit 1";
my $lastid = $dbh->selectrow_array($queryID);

一切正常,但当我尝试首先执行此操作时,脚本会在此行停止响应:

while($sth->fetch) {

我尝试调试代码,查找教程,阅读大量页面,无法确定问题所在:(

问候。

** * * 更新 * ** < EM> * ****

我认为在经过一些调试之后我发现了问题但不是解决方案。在第二个名为$ query的sql上,我传递了第一个sql上的变量$ lastid,参见:

my $query = "SELECT stuff from table join things where event.id > **$lastid** and blablabla

如果我更改$ lastid,例如,13330506,一切正常,所以似乎存在关于如何传递此变量的问题。奇怪的是,当我在$ lastid的内容中使用$ lastid打印$ query是正确的时,这个数字显得很奇怪,至少对我而言。

1 个答案:

答案 0 :(得分:1)

如果您阅读文档http://search.cpan.org/dist/DBI/DBI.pm 你会看到没有 - &gt; fetch函数,但是有各种提取方法:

@row_ary  = $sth->fetchrow_array;
$ary_ref  = $sth->fetchrow_arrayref;
$hash_ref = $sth->fetchrow_hashref;

$ary_ref  = $sth->fetchall_arrayref;
$ary_ref  = $sth->fetchall_arrayref( $slice, $max_rows );

$hash_ref = $sth->fetchall_hashref( $key_field );

每一个都返回一个你应该存储在变量中的引用供以后使用,例如:

while ( @row = $sth->fetchrow_array ) { ... }
while (my $data = $sth->fetchrow_hashref) { ... }

然后,您可以在循环中使用@row或$ data来检索所需的数据。