2012-10-13 75 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]'是'@ _'數組的第二個元素。 –