2012-10-13 50 views
0

我想根据用户输入在MySQL中创建一个表。理想情况下,Perl脚本将连接到数据库并使用从用户接收的变量创建表。这里是我的脚本:麻烦在MySQL中使用Perl创建一个变量表

print "Please enter a name for the table: "; 
$tableName = <>; 
chomp($tableName); 
&createTable ($tableName); 

sub createTable 
{ 
    use DBI; 
    my $platform = "mysql"; 
    my $database = "example"; 
    my $host = "localhost"; 
    my $user = "user"; 
    my $pw = "pw"; 
    my $dsn = "dbi:$platform:$database:$host"; 
    my $dbh = DBI->connect($dsn, $user, $pw) or die "Unable to connect: $DBI::errstr\n"; 
    $dbh->do("DROP TABLE IF EXISTS $_"); 
    $dbh->do("CREATE TABLE $table (column VARCHAR(17))"); 
    $dbh->disconnect; 
} 

但是,当我执行脚本,并输入一个值(比方说,“测试”),就脱口而出这回我:

DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 at /path/to/scripts/dbTest.pl line 28, <> line 2. 
DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(column VARCHAR(17))' at line 1 at /path/to/scripts/dbTest.pl line 29, <> line 2. 

第28行是DROP命令,第29行是CREATE命令。 我检查了我的语法很多次,但我似乎并没有得到错误在哪里。我能忽略那么简单的事情吗?

回答

1

试一下:

use warnings; use strict; 
use DBI; 
print "Please enter a name for the table: "; 
$tableName = <>; 
chomp($tableName); 
createTable($tableName); 

sub createTable { 
    my $table = shift; 

    my $platform = "mysql"; 
    my $database = "example"; 
    my $host = "localhost"; 
    my $user = "user"; 
    my $pw = "pw"; 
    my $dsn = "dbi:$platform:$database:$host"; 
    my $dbh = DBI->connect($dsn, $user, $pw) 
     or die "Unable to connect: $DBI::errstr\n"; 
    $dbh->do("DROP TABLE IF EXISTS $table"); 
    $dbh->do("CREATE TABLE $table (column VARCHAR(17))"); 
    $dbh->disconnect; 
} 

你不能在你的函数使用$_这样。您必须改为处理@_(或像我一样使用shift)。看到perldoc perlsub

+0

那么,这绝对是诀窍!尽管你可以使用@_,$ _ [0-inf]和$ _,我认为我已经阅读过某处。除非我误解了它的OP。 [这里](http://www.comp.leeds.ac.uk/Perl/subroutines.html) 正下方的“参数”部分。我现在看到他的意思是你可以使用它,但不是作为传递给子程序的参数。 谢谢! – Arkevius

+0

'$ _'是默认变量。 '@ _'是默认数组。 '$ _ [1]'是'@ _'数组的第二个元素。 –