简体   繁体   English

如何使用Perl将MySQL表的内容转储到文件?

[英]How do I dump contents of a MySQL table to file using Perl?

What's the best way to dump a MySQL table to a file in Perl? 将MySQL表转储到Perl文件的最佳方法是什么?

I've been using: 我一直在用:

open( FILE, ">$filename" );
my $sth=$dbh->prepare("select * from table");
$sth->execute();
while ( my $row = $sth->fetchrow_arrayref ) {
    print FILE join( "|", @$row ), "\n";
}

Can you shell out to mysqldump ? 你可以炮击mysqldump吗? That's what it's there for... 这就是它的用途......

It depends on what you really want. 这取决于你真正想要的。 Do you want to preserve schema information and database metadata? 您想保留架构信息和数据库元数据吗? What about column names? 列名怎么样? On the other hand your current method should work fine for data storage as long as the schema and column order don't change, buy you should consider the case of some record with the "|" 另一方面,只要架构和列顺序没有改变,你当前的方法应该可以正常工作数据存储,买你应该考虑一些带有“|”的记录的情况 character in it and escape that value appropiately, and apply the corresponding logic when you read and parse the file back. 其中的字符并适当地转义该值,并在您读取并解析文件时应用相应的逻辑。 You might want to look into Text::CSV for a fast, realiable and flexible implementation that does most of the work for you in both directions, both writing an reading the file. 您可能希望查看Text :: CSV以获得快速,可靠且灵活的实现,该实现可以在两个方向上完成大部分工作,同时编写读取文件。

As already said, it depends on what you want to do. 如前所述,这取决于你想做什么。 If the purpose is to back up the data, you should consider mysqlhotcopy (if you are using MyIsam tables) which copies the data/index files. 如果目的是备份数据,则应考虑复制数据/索引文件的mysqlhotcopy (如果使用的是MyIsam表)。 It is much faster than manually dumping data (eg I get a 2.5 gb backup in approx 3 minutes). 它比手动转储数据快得多(例如,我在大约3分钟内获得2.5 GB的备份)。

Depending on why you need it dumped and what the size and content is. 取决于您需要倾倒的原因以及大小和内容。 Assuming what you want is not a backup, which obviously should have a different application besides perl for. 假设你想要的不是备份,除了perl之外,它显然应该有不同的应用程序。 I would go with something like this which will preserve your columns and make the data easier in some respects to slurp into other programs or hand off than a CSV. 我会选择这样的东西,这将保留你的列,并使数据更容易在某些方面进入其他程序或交出比CSV。

use XML::Simple;
...
my @rows=();
while ( my $h = $sth->fetchrow_hashref() )
{
   $h->{_ROWNUM}=$#rows;
   push(@rows, $h);
}
print XMLout(\@rows);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM