【发布时间】:2011-03-17 23:30:58
【问题描述】:
我对使用 MySQL 很陌生,而且是 Perl 的新手,但我试图破解别人的脚本来帮助我。我从here 得到了脚本。到目前为止它看起来很棒,但是由于表正在进行一些外键检查,所以它失败了。我可以通过 phpmyadmin 并尝试将它们全部删除,但这需要永远,并且是我第三次必须这样做:( 我的问题是,可以将此脚本修改为包括:
`SET FOREIGN_KEY_CHECKS = 0;
在它运行 drop table 命令之前?我试图按照脚本进行操作,但找不到脚本的明确命令部分(可能是由于无知/缺乏理解)。非常感谢任何帮助。
#!/usr/bin/perl
use strict;
use DBI;
my $hostname = '';
my $database = '';
my $username = '';
my $password = '';
my $dbh = DBI->connect("dbi:mysql:${database}:$hostname",
$username, $password) or die "Error: $DBI::errstr\n";
my $sth = $dbh->prepare("SHOW TABLES");
$sth->execute or die "SQL Error: $DBI::errstr\n";
my $i = 0;
my @all_tables = ();
while(my $table = $sth->fetchrow_array)
{
$i++;
print "table $i: $table\n";
push @all_tables, $table;
}
my $total_table_count = $i;
print "Enter string or regex to match tables to "
. "delete (won't delete yet): ";
my $regex = <STDIN>;
chomp $regex;
$i = 0;
my @matching_tables = ();
foreach my $table (@all_tables)
{
if($table =~ /$regex/i)
{
$i++;
print "matching table $i: $table\n";
push @matching_tables, $table;
}
}
my $matching_table_count = $i;
if($matching_table_count)
{
print "$matching_table_count out of $total_table_count "
. "tables match, and will be deleted.\n";
print "Delete tables now? [y/n] ";
my $decision = <STDIN>;
chomp $decision;
$i = 0;
if($decision =~ /y/i)
{
foreach my $table (@matching_tables)
{
$i++;
print "deleting table $i: $table\n";
my $sth = $dbh->prepare("DROP TABLE $table");
$sth->execute or die "SQL Error: $DBI::errstr\n";
}
}
else
{
print "Not deleting any tables.\n";
}
}
else
{
print "No matching tables.\n";
}
【问题讨论】:
-
您想无限期地删除外键,还是让它们在您使用数据库时暂时不检查任何内容?
-
(附带说明,perl 代码可能是:
my $sth = $dbh->prepare("SET FOREIGN_KEY_CHECKS = 0;");$sth->execute) -
如果您再也不会使用准备好的句柄,您可以使用
->do代替准备/执行对 :) -
谢谢 Wrikken,等我鼓起勇气再去试试!