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;
}

しかし、スクリプトを実行して値を入力すると(たとえば、「test」)、これがぼやけてしまいます。

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 に答える