简体   繁体   中英

perl DBI grant privileges

Please help understand what I'm doing wrong here. I guess escaping is wrong, but I can't google a workable example.

my $host = "localhost";
my $port = "3306";
my $user = "root";
my $pass = "111";
my $db_name = "test";
my $db_user = "test";
my $db_pass = "test";

my $dsn = "dbi:mysql::$host:$port";
my $dbh = DBI->connect($dsn, $user, $pass) or die "Unable to connect: $DBI::errstr\n";

$dbh->do("CREATE DATABASE $db_name");
$dbh->do("CREATE USER $db_user\@$host");
$dbh->do("GRANT ALL ON $db_name.* TO $db_user\@$host IDENTIFIED BY $db_pass");

$dbh->disconnect();

Error:

DBD::mysql::db do failed: Operation CREATE USER failed for 'test'@'localhost' at /home/andrew/sandbox/script.pl line 42.
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 'test' at line 1 at /home/andrew/sandbox/script.pl line 43.

Thank you for answers.

You need to quote the password.

$dbh->do("GRANT ALL ON $db_name.* TO $db_user\@$host IDENTIFIED BY '$db_pass'");
                                                                   ^        ^

Though of course prepared statements/parameters would be much better (if MySQL allows them here, which I'm not 100% sure of).

You should quote the $db_user and $host as well (again, assuming parameters don't work).

If parameters work:

$dbh->do(q{GRANT ALL ON ?.* TO ?@? IDENTIFIED BY ?}, {}, $db_name, $db_user, $host, $db_pass);

I'm fairly confident parameters will work on the password, and probably also on user and host. The database name, I'm not so sure of. You may just have to inline it with quote_identifier .

edit: You should just strike the CREATE USER line entirely. Granting permissions will create the user (and with a password).

似乎您每次运行脚本时都在尝试创建用户-如果我尝试多次创建用户,则会收到确切的错误消息。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM