2011-10-31 152 views
0

請幫助理解我在這裏做錯了什麼。我想轉義是錯誤的,但我不能谷歌一個可行的例子。perl DBI授予權限

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(); 

錯誤:

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. 

感謝您的答案。

回答

1

您需要引用密碼。

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

雖然當然準備語句/參數會更好(如果MySQL允許他們在這裏,我敢肯定不是100%)。

您應該引用$db_user$host(同樣,假設參數不起作用)。

如果參數工作:

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

我相當有信心參數將在密碼工作,並且也可能對用戶和主機。數據庫名稱,我不太確定。你可能只需要與quote_identifier聯繫。

編輯:你應該完全擊中CREATE USER行。授予權限將創建用戶(並使用密碼)。

+0

對不起,我沒有給你,$ password包含一個簡單的字符串,沒有空格,錯誤指向'create user'和'grant'命令 – Andrew

+0

@lush:[GRANT語法](http:// dev.mysql.com/doc/refman/5.5/en/grant.html)需要密碼的單引號。你沒有他們。所以你得到一個語法錯誤。 – derobert

+0

解決了。是的,引用不適用於用戶,但我只是評論'創建用戶'字符串,因爲它不是強制性的。謝謝) – Andrew

0

看起來您每次運行腳本時都會嘗試創建用戶 - 如果我嘗試多次創建用戶,則會出現確切的錯誤。

+0

你是對的!我放棄了用戶,並將其引用爲'$ db_user'\ @'$ host',現在它已完全正常工作。謝謝) – Andrew