您可以通过创建数据库 API 来解决此问题。SQL 代码应该可以帮助您。
CREATE TABLE mysql.`created_users` (
`user_name` varchar(255) DEFAULT NULL,
`owner` varchar(255) DEFAULT NULL
)
该表包含用户名以及创建它们的用户。
注意使用您的 root 帐户创建程序
创建 mysql 用户的过程。
DROP PROCEDURE IF EXISTS mysql.createUser;
DELIMITER //
CREATE PROCEDURE mysql.createUser(IN userName VARCHAR(255), IN userPassword VARCHAR(255))
BEGIN
SET @createUserQuery = CONCAT('
CREATE USER "',userName,'"@"localhost" IDENTIFIED BY "',userPassword,'" '
);
PREPARE stmt FROM @createUserQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @createcreatedUserQuery = CONCAT('
INSERT INTO mysql.created_users (user_name, owner) VALUE("',userName,'", "',USER(),'")'
);
PREPARE stmt FROM @createcreatedUserQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
删除程序并检查 created_users 表以确保用户存在并删除权限检查。
DROP PROCEDURE IF EXISTS mysql.dropUser;
DELIMITER //
CREATE PROCEDURE mysql.dropUser(IN userName VARCHAR(255))
BEGIN
SET @canDeleteUser = 0;
SET @createCountUserQuery = CONCAT('
SELECT COUNT(*) FROM mysql.created_users WHERE user_name = "',userName,'" AND owner = "',USER(),'" INTO @canDeleteUser'
);
PREPARE stmt FROM @createCountUserQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
IF @canDeleteUser = 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'The user is not known on the server or you dont have rights to delete this user';
END IF;
IF @canDeleteUser = 1 THEN
SET @createDropUserQuery = CONCAT('
DROP USER "',userName,'"@"localhost"'
);
PREPARE stmt FROM @createDropUserQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @createDeleteUserQuery = CONCAT('
DELETE FROM created_users WHERE user_name = "',userName,'" AND owner = "',USER(),'"'
);
PREPARE stmt FROM @createDeleteUserQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END //
DELIMITER ;
并赋予执行这些的权利
GRANT EXECUTE ON PROCEDURE mysql.createUser TO '[user]'@'localhost';
GRANT EXECUTE ON PROCEDURE mysql.dropUser TO '[user]'@'localhost';
您可能希望在 mysql.proc 上为用户提供 select priv,以便他们可以看到程序背后的源代码并了解参数
您可以像这样使用数据库 API。
CALL mysql.createUser('user', 'password');
CALL mysql.dropUser('user');
请注意,root 帐户只能删除具有所有者 root@localhost 的 mysql.dropUser 用户