代码之家  ›  专栏  ›  技术社区  ›  Ian Kemp

如何通用/动态创建/删除用户

  •  0
  • Ian Kemp  · 技术社区  · 16 年前

    (与…有关,但与…分开 Syntax error with emulating "create user if not exists" 。)

    是否可以实现一般/动态添加用户的功能(即模拟 sp_adduser mysql中是否包含其他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 ;
    
    1 回复  |  直到 16 年前
        1
  •  0
  •   Question Mark    16 年前

    INSERT INTO ...... ON DUPLICATE KEY UPDATE ......=VALUE(.....)