2013-09-25 40 views
2

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

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) { 

我试图调试代码,寻找教程,阅读了很多页面,并且无法确定问题出在哪里:(

此致敬礼。

** * * UPDATE * ** * ****

我想我发现这个问题后,一些更多的调试,但不是解决办法。在第二个SQL命名为$查询我通过变量$ lastid,我得到的第一个SQL,请参阅:

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

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

回答

1

如果你阅读文档http://search.cpan.org/dist/DBI/DBI.pm 你会看到有没有 - >取功能,但也有不同的方法获取:

@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来检索所需的数据。

+2

其实,有一个'fetch'方法。这是'fetchrow_arrayref'的别名。 – cjm

+0

更新信息,我想我找到了问题,但不是解决方案:S – user2772936

+0

好的,所以,解决方案发现,很容易,我是白痴。我在索要一堆比数据库上最后一个ID更大的id:facepalm:对不起浪费你的时间。 – user2772936

相关问题