0

我正在尝试根据用户输入在 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 命令。我已经检查了很多次我的语法,但我似乎没有得到错误的位置。我是否忽略了如此简单的事情..?

4

1 回答 1

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

于 2012-10-13T21:53:30.770 回答