MySQL: Check if the user exists and drop it

前端 未结 14 1686
遇见更好的自我
遇见更好的自我 2020-12-02 16:43

There’s not standard way to check if a MySQL user exists and based on that drop it. Are there any workarounds for this?

Edit: I need a straight way to run this wi

相关标签:
14条回答
  • 2020-12-02 17:08

    Regarding @Cherian's answer, the following lines can be removed:

    SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ANSI';
    ...
    SET SQL_MODE=@OLD_SQL_MODE;
    ...
    

    This was a bug pre 5.1.23. After that version these are no longer required. So, for copy/paste convenience, here is the same with the above lines removed. Again, for example purposes "test" is the user and "databaseName" is the database; and this was from this bug.

    DROP PROCEDURE IF EXISTS databaseName.drop_user_if_exists ;
    DELIMITER $$
    CREATE PROCEDURE databaseName.drop_user_if_exists()
    BEGIN
      DECLARE foo BIGINT DEFAULT 0 ;
      SELECT COUNT(*)
      INTO foo
        FROM mysql.user
          WHERE User = 'test' and  Host = 'localhost';
       IF foo > 0 THEN
             DROP USER 'test'@'localhost' ;
      END IF;
    END ;$$
    DELIMITER ;
    CALL databaseName.drop_user_if_exists() ;
    DROP PROCEDURE IF EXISTS databaseName.drop_users_if_exists ;
    
    CREATE USER 'test'@'localhost' IDENTIFIED BY 'a';
    GRANT ALL PRIVILEGES  ON databaseName.* TO 'test'@'localhost'
     WITH GRANT OPTION
    
    0 讨论(0)
  • 2020-12-02 17:10
    DROP USER IF EXISTS 'user'@'localhost' ;
    

    that works for me without throwing any errors in Maria DB, it should work for u too

    0 讨论(0)
提交回复
热议问题