0

(与模拟“如果不存在则创建用户”有关,但与语法错误不同。)

是否可以在 MySQL 中实现通用/动态添加用户(即模拟sp_adduser其他 DBMS 中包含的系统过程)的功能?

MySQL 不支持以下if [not] exists语法,请参阅http://bugs.mysql.com/bug.php?id=15287

create user if not exists 'foo'@'%' identified by password 'bar';

它也不支持这个:

drop procedure if exists create_user_if_not_exists;

delimiter ||

create procedure create_user_if_not_exists
               ( sUser     varchar(60),
                 sHost     varchar(16),
                 sPassword varchar(255) )
begin

-- ensure user does not yet exist
if (select ifnull((select 1
                     from mysql.user
                    where User = sUser
                      and Host = sHost), 0) = 0) then
  set @createUserText = concat('create user ''', sUser, '''@''', sHost, ''' identified by ''', sPassword, ''';');

  prepare createUserStatement FROM @createUserText;
  execute createUserStatement;
  deallocate prepare createUserStatement;
end if;

end ||

delimiter ;

因为如果您尝试调用所述程序:

call create_user_if_not_exists ( 'foo', '%', 'bar' );

你收到了可爱的信息:

This command is not supported in the prepared statement protocol yet

以下工作,但显然不是特别可重用:

drop procedure if exists create_user_if_not_exists;

delimiter ||

create procedure create_user_if_not_exists
               (  )
begin

if (select ifnull((select 1
                     from mysql.user
                    where User = 'foo'
                      and Host = '%'), 0) = 0) then
  create user 'foo'@'%' identified by password 'bar';
end if;

end ||

delimiter ;
4

1 回答 1

0

哦,对不起,我刚刚说你在谈论数据库用户。不是应用程序用户。

你可能会喜欢这种INSERT INTO ...... ON DUPLICATE KEY UPDATE ......=VALUE(.....)说法。

我在我的一般保存对象方法中使用它,使用它我不必关心用户是否存在,在我提交后它会在那里(并且是最新的)。

于 2009-10-01T11:48:23.907 回答