2011-02-25 65 views
1

我的测试脚本只是执行到mysql数据库的perl dbi连接,并给出一个表的列表,提取(1)每个表的记录。perl - 帮助修改代码以包含子例程的使用

对于我列出的每个表格,我还想打印出(1)记录到其自己的文件。例如,如果我有一个100个表的列表,我应该预期每个100个独立文件(1)个记录。

到目前为止代码工作,但我有兴趣创建一个子程序,称之为create_file为处理该#Create file

我不熟悉的写作子例程和需要协助,如果代码段可能。 我不知道如何调用数据构建的部分。 $data='';

有人可以告诉我很好的方法吗?谢谢你的帮助。

代码:

# Get list of tables 
my @tblist = qx(mysql -u foo-bar -ppassw0rd --database $dbsrc -h $node --port 3306 -ss -e "show tables"); 

# Data output 
    foreach my $tblist (@tblist) 
    { 
     my $data = ''; 
     chomp $tblist; 

     #Create file 
     my $out_file = "/home/$node-$tblist.$dt.dat"; 
     open (my $out_fh, '>', $out_file) or die "cannot create $out_file: $!"; 

     my $dbh = DBI->connect("DBI:mysql:database=$dbsrc;host=$node;port=3306",'foo-bar','passw0rd'); 
     my $sth = $dbh->prepare("SELECT UUID(), '$node', ab, cd, ef, gh, hi FROM $tblist limit 1"); 
     $sth->execute(); 
      while (my($id, $nd,$ab,$cd,$ef,$gh,$hi) = $sth->fetchrow_array()) { 
      $data = $data. "__pk__^A$id^E1^A$nd^E2^A$ab^E3^A$cd^E4^A$ef^E5^A$gh^E6^A$hi^E7^D"; 
      } 
      $sth->finish; 
      $dbh->disconnect; 

     #Create file 
     print $out_fh $data; 
     close $out_fh or die "Failed to close file: $!"; 
    }; 

回答

2
my $dt = "2011-02-25"; 
my $dbsrc = "..."; 
my $node = "..."; 

# Get list of tables 
my @tblist = qx(mysql -u foo-bar -ppassw0rd --database $dbsrc -h $node --port 3306 -ss -e "show tables"); 
my $dbh = DBI->connect("DBI:mysql:database=$dbsrc;host=$node;port=3306",'foo-bar','passw0rd'); 
foreach my $tblist (@tblist) 
{ 
    # This breaks - chomp is given a list-context 
    #extract_data($dbh, chomp($tblist)); 
    chomp $tblist; 
    extract_data($dbh, $tblist); 
}; 
$dbh->disconnect; 

sub extract_table 
{ 
    my($dbh, $tblist) = @_; 

    my $out_file = "/home/$node-$tblist.$dt.dat"; 
    open (my $out_fh, '>', $out_file) or die "cannot create $out_file: $!"; 

    my $sth = $dbh->prepare("SELECT UUID(), '$node', ab, cd, ef, gh, hi FROM $tblist limit 1"); 
    $sth->execute(); 
    while (my($id, $nd,$ab,$cd,$ef,$gh,$hi) = $sth->fetchrow_array()) { 
     print $out_fh "__pk__^A$id^E1^A$nd^E2^A$ab^E3^A$cd^E4^A$ef^E5^A$gh^E6^A$hi^E7^D"; 
    } 
    $sth->finish; 

    close $out_fh or die "Failed to close file: $!"; 
}; 

,除非你真的需要连接到数据库为您执行每个语句,保持数据库操作期间开放。

+0

对,我不需要每次连接每个tbl。一个持久连接都是需要提取信息的id。谢谢。 – cjd143SD 2011-02-25 19:07:56

+0

@ cjd143SD:你可能会发现DBI中有一个方法可以直接获取表名列表,避免'qx()'操作:'my @tables = $ dbh-> tables;'? – 2011-02-25 19:15:58

+0

不知道为什么我在fetchrow_array失败时出错。 DBD :: mysql :: st执行失败:您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以在'1 limit 1'附近使用正确的语法。我认为sql很好。它的工作之前。 – cjd143SD 2011-02-25 20:31:34

2

您可以使用File::Slurpwrite_file来代替自己创建create_file。 它提取开放/关闭/死亡/打印。