首先,确保你已经安装了mysql-connector-python库,如果还没有安装,可以使用以下命令进行安装
pip install mysql-connector-python
然后,这是Python脚本的内容
import mysql.connector
from mysql.connector import Error
def create_user(host_name, user_name, user_password, new_user_name, new_user_password, db_name):
# 创建数据库连接
connection = mysql.connector.connect(host=host_name,
user=user_name,
passwd=user_password)
cursor = connection.cursor()
try:
# 创建新用户
cursor.execute(f"CREATE USER '{
new_user_name}'@'localhost' IDENTIFIED BY '{
new_user_password}';")
# 授予新用户对指定数据库的所有权限
cursor.execute(f"GRANT ALL PRIVILEGES ON {
db_name} . * TO '{
new_user_name}'@'localhost';")
# 提交修改
connection.commit()
print(f"User {
new_user_name} created successfully.")
except Error as e:
print(f"Error: '{
e}'")
finally:
# 关闭数据库连接
cursor.close()
connection.close()
# 使用你的MySQL服务器详细信息替换下面的值
host_name = "localhost"
user_name = "root"
user_password = "rootpassword"
# 创建的新用户的用户名和密码
new_user_name = "newuser"
new_user_password = "newpassword"
# 要授予权限的数据库
db_name = "mydatabase"
create_user(host_name, user_name, user_password, new_user_name, new_user_password, db_name)
当你运行这个脚本时,它将连接到MySQL服务器,创建一个新用户,并授予该用户对指定数据库的所有权限。
注意:请确保你有足够的权限来创建用户和授予权限,并且使用这个脚本时要非常小心,因为它涉及到数据库安全。