简体   繁体   English

perl DBI授予特权

[英]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. 我想转义是错误的,但我无法在Google上找到一个可行的示例。

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). 尽管当然准备好的语句/参数会更好(如果MySQL在这里允许它们,我不是100%肯定的)。

You should quote the $db_user and $host as well (again, assuming parameters don't work). 您还应该引用$db_user$host (同样,假设参数不起作用)。

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 . 您可能只需要使用quote_identifier对其进行内联。

edit: You should just strike the CREATE USER line entirely. 编辑:您应该只完全点击CREATE USER行。 Granting permissions will create the user (and with a password). 授予权限将创建用户(并使用密码)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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