【问题标题】:Trouble Creating Table with a variable using Perl in MySQL在 MySQL 中使用 Perl 创建带变量的表时遇到问题
【发布时间】:2026-02-22 19:45:02
【问题描述】:

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

【问题讨论】:

    标签: mysql perl ubuntu syntax-error create-table


    【解决方案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-inf] 和 $_。除非我误解了它的OP。 HERE 在“参数”部分的正下方。我现在明白他的意思是你可以使用它,但不能作为传递给子例程的参数。谢谢!
    • $_ 是默认变量。 @_ 是默认数组。 $_[1]@_ 数组的第二个元素。