【问题标题】:How to generically/dynamically create/drop users如何一般/动态地创建/删除用户
【发布时间】:2009-10-01 11:36:53
【问题描述】:

(与Syntax error with emulating "create user if not exists" 相关但独立。)

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

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 ;

【问题讨论】:

    标签: mysql database missing-features


    【解决方案1】:

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

    您可能会喜欢INSERT INTO ...... ON DUPLICATE KEY UPDATE ......=VALUE(.....) 声明。

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

    【讨论】:

    • 是的,这就是我最终的结果。不过感觉不是特别干净……
    猜你喜欢
    • 2020-07-04
    • 2013-01-16
    • 2010-09-29
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多